允许在 Rails 5 中使用 FriendlyId 和 Ancestry Gem 重复 slug

Allow duplicate slugs with FriendlyId & Ancestry Gem in Rails 5

我在 Rails 5 应用程序中使用 FriendlyId & Ancestry Gem。我正在为我的主要服务创建筒仓营销页面,并且需要创建位于不同祖先父路径上的重复 slug。我在下面包含了我的初始种子文件以供参考。

如你所见,我的根路径是:

www.mysite.com
www.mysite.com/events
www.mysite.com/events/san-diego
www.mysite.com/events/orange-county
www.mysite.com/events/los-angeles
www.mysite.com/events/riverside

** 这是我需要的重复 slug **

www.mysite.com/events/san-diego/birthday-parties
www.mysite.com/events/orange-county/birthday-parties
www.mysite.com/events/los-angeles/birthday-parties
www.mysite.com/events/riverside/birthday-parties
...

如您所见,尽管 slug 是重复的,但它们位于不同的父路径之外。我如何根据父项验证 slug,以便创建重复的 slug?

** db/seeds.rb **

home = Page.create(title: 'Home')

# home/events
events = Page.create(title: 'Events', parent: home)

# home/events/cityPage
san_diego = Page.create(title: 'San Diego', parent: events)
orange_county = Page.create(title: 'Orange County', parent: events)
los_angeles = Page.create(title: 'Los Angeles', parent: events)
riverside = Page.create(title: 'Riverside', parent: events)

# home/events/san-diego/eventPage
Page.create(title: 'Birthday Parties', parent: san_diego)
Page.create(title: 'School Events', parent: san_diego)
Page.create(title: 'Church Events', parent: san_diego)
Page.create(title: 'Corporate Events', parent: san_diego)
Page.create(title: 'Social Events', parent: san_diego)
Page.create(title: 'Community Events', parent: san_diego)

# home/events/orange-county/eventPage
Page.create(title: 'Birthday Parties', parent: orange_county)
Page.create(title: 'School Events', parent: orange_county)
Page.create(title: 'Church Events', parent: orange_county)
Page.create(title: 'Corporate Events', parent: orange_county)
Page.create(title: 'Social Events', parent: orange_county)
Page.create(title: 'Community Events', parent: orange_county)

# home/events/los-angeles/eventPage
Page.create(title: 'Birthday Parties', parent: los_angeles)
Page.create(title: 'School Events', parent: los_angeles)
Page.create(title: 'Church Events', parent: los_angeles)
Page.create(title: 'Corporate Events', parent: los_angeles)
Page.create(title: 'Social Events', parent: los_angeles)
Page.create(title: 'Community Events', parent: los_angeles)

# home/events/riverside/eventPage
Page.create(title: 'Birthday Parties', parent: riverside)
Page.create(title: 'School Events', parent: riverside)
Page.create(title: 'Church Events', parent: riverside)
Page.create(title: 'Corporate Events', parent: riverside)
Page.create(title: 'Social Events', parent: riverside)
Page.create(title: 'Community Events', parent: riverside)

** 显示添加到重复 slug 的哈希的数据库屏幕截图 **

您可以使用范围 validates_uniqueness_of。

例如

validates_uniqueness_of :slug, scope: :parent_id

这样做,它将验证该记录的唯一性,但如果 parent_id 不同,则允许相同的 slug