【发布时间】: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