【问题标题】:How to set Rails polymorphic model with friendly_id and history如何使用friendly_id和历史设置Rails多态模型
【发布时间】:2019-03-13 09:01:34
【问题描述】:

我有一个公司和 Seo 模型(位于 Seo 下方的链接中,称为 PublicSlug),它具有多态关联和类似问题的回答
Match multiple models in single Rails route with friendly_id

只要我添加 :history 选项,就可以建立关注点。
当我在 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 中不明确的数据库列

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

models/company.rb

class Company < ApplicationRecord
  include Sluggable

  belongs_to :city

end

models/concerns/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】:

    更改多态的sluggable名称时,将解决数据库中的冲突歧义列。 Friendly_id 也使用 sluggable_id 和 sluggable_type 来记录历史。

    class Seo < ApplicationRecord
    
      extend FriendlyId
      
      ... 
      belongs_to :sluggable, polymorphic: true
      #this line was problem
      
    
      ...
    
    end

    【讨论】:

    • @MayurShah 感谢您提供更好的格式。这是我的第一篇文章。
    猜你喜欢
    • 1970-01-01
    • 2012-07-06
    • 1970-01-01
    • 1970-01-01
    • 2017-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多