如何使用friendly_id和history设置Rails多态模型

问题描述 投票:0回答:1

我有一个公司和Seo模型(在Seo下面的链接称为Public Slug),具有类似于答案的多态关联和关注 Match multiple models in single Rails route with friendly_id

只要我添加:历史选项,建立关注和所有工作。 之后我在rails控制台中更新Seo时出错了

Traceback (most recent call last):
        3: from (irb):3
        2: from app/models/concerns/sluggable.rb:17:in `touch_seo'
        1: from app/models/seo.rb:28:in `update_slug'
ActiveRecord::StatementInvalid (Mysql2::Error: Column 'sluggable_id' in where clause is ambiguous: SELECT  1 AS one FROM `seos` INNER JOIN `friendly_id_slugs` ON `friendly_id_slugs`.`sluggable_id` = `seos`.`id` AND `friendly_id_slugs`.`sluggable_type` = 'Seo' WHERE `seos`.`id` != 10 AND (sluggable_id <> 10) AND `seos`.`slug` = 'san-fransisco2' LIMIT 1)

如何使用:history选项解决friendly_id中的ambigous数据库列

models.seo.rb

class Seo < ApplicationRecord

  extend FriendlyId
  
  friendly_id :set_candidates, use: [:slugged, :history ] 
  belongs_to :sluggable, polymorphic: true
  validates :slug, presence: true, uniqueness: { case_sensitive: false }


  def should_generate_new_friendly_id?
    true
    #always 
  end

  def update_slug
    self.should_generate_new_friendly_id?
    self.save!
  end

  private
  def set_candidates
    case sluggable_type
    when 'Company' then company_candidates
    when 'City' then city_candidates
    end
  end

  def company_candidates
    [ 
      sluggable.name,
      ["#{sluggable.name} w mieście #{sluggable.city.name} na ulicy #{sluggable.street}"]
    ]
  end

  def city_candidates
    [ sluggable.name ]
  end


end

车型/ company.rb

class Company < ApplicationRecord
  include Sluggable

  belongs_to :city

end

车型/关注/ sluggable.rb

module Sluggable
  extend ActiveSupport::Concern

  included do
    before_validation :create_seo
    has_one :seo, dependent: :destroy, as: :sluggable
    after_update :touch_seo
    #delegate :slug, to: :seo, prefix: :setting
    #line above is unnecessary

    private
      def create_seo
        self.seo = Seo.new unless seo.present?
      end

      def touch_seo
        self.seo.update_slug
      end
  end
end
ruby-on-rails polymorphic-associations friendly-id
1个回答
0
投票

当改变多态的可缓冲名称时,数据库中的冲突模糊列将被解析。 Friendly_id也使用sluggable_idsluggable_type作为历史。

class Seo < ApplicationRecord

  extend FriendlyId
  
  ... 
  belongs_to :sluggable, polymorphic: true
  #this line was problem
  

  ...

end
© www.soinside.com 2019 - 2024. All rights reserved.