我有 Attraction 和 Venue 模型。它们的关联是:Attractionbelongs_to :venueVenuehas_many :attractions,dependent: :nullify我正在使用friendly_id gem 为两者添加 slug。它们...
我有 Attraction
鸭子 Venue
模型。他们的协会是:
Attraction
belongs_to :venue
Venue
has_many :attractions, dependent: :nullify
我使用 friendly_id
gem 为两者添加了 slug。添加方式如下:
Attraction
friendly_id :slugged_name_and_venue, use: :slugged
Venue
friendly_id :slugged_name_and_location, use: :slugged
我遇到的问题是,由于 Attraction slug 包含 name
的 location_1
和 venue
,如果 name
或 location_1
属性发生更改,则 Attraction 的 slug 不正确。我需要更新它们以始终保持同步。
p4
p5
我尝试了多种选项,但没有一个能够真正成功更新相关的景点。
我最近的尝试是这样的:
Venue
def should_generate_new_friendly_id?
slug.blank? || name_changed? || location_1_changed?
end
after_update :update_attraction_slugs, if: :should_update_attraction_slugs?
private
def should_update_attraction_slugs?
saved_change_to_name? || saved_change_to_location_1?
end
def update_attraction_slugs
attractions.find_each(&:save)
end
Attraction
def should_generate_new_friendly_id?
slug.blank? || slug_changed? || name_changed? || full_name_changed? || venue_id_changed? || venue_name_or_location_1_changed?
end
def venue_name_or_location_1_changed?
saved_change_to_attribute?(:venue_id) || venue.saved_change_to_name? || venue.saved_change_to_location_1?
end
有人能帮我吗?
提前致谢!