Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Friendly ID 4 Using scoped module

I can't work this out. Using the documentation

I have two models

class Region < ActiveRecord::Base
  extend FriendlyId
  has_many :pages
  friendly_id :name, :use => :slugged
end

class Page < ActiveRecord::Base

  extend FriendlyId      
  belongs_to :region
  friendly_id :name, :use => :scoped, :scope => :region
end

According to the documentation this should work. But when I create a page it's not creating a slug via a scope, and this means when I create another page with the same name I get duplicate index error.

like image 939
j-dexx Avatar asked Jun 10 '26 15:06

j-dexx


1 Answers

If you are currently indexing your pages on the slug field with something like this:

add_index :page, :slug, :unique => true

then you might want to swap that for an index on both the slug and the region:

remove_index :page, :slug
add_index :page, [:slug, :region_id], :unique => true

The documentation describes how to start using :history and :scoped together in FriendlyId 5, maybe that could give you some ideas on how to solve it in your case: http://rubydoc.info/github/norman/friendly_id/master/file/README.md#Upgrading_from_FriendlyId_4_0


Or, you could just remove the uniqueness constraint, as I now see that you have replied to my original comment. :)

remove_index :page, :slug
add_index :page, :slug # no :unique here
like image 65
lime Avatar answered Jun 13 '26 05:06

lime



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!