允许使用FriendlyId& amp; Rails中的祖先宝石5

时间:2017-10-27 17:45:56

标签: ruby-on-rails ruby ruby-on-rails-5 friendly-id ancestry

我正在使用FriendlyId&我的Rails 5应用中的Ancestry Gem。我正在为我的主要服务创建silo营销页面,并且需要创建位于不同祖先父路径上的重复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

**以下是我需要的重复slu ** **

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
...

正如您所看到的,虽然slu is是重复的,但它们却坐在不同的父路径上。如何根据父级验证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)

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

enter image description here

1 个答案:

答案 0 :(得分:1)

您可以将validates_uniqueness_of与范围一起使用。

例如

validates_uniqueness_of :slug, scope: :parent_id

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