Friendly ID 4 Using scoped module

狂风中的少年 提交于 2019-12-10 10:05:57

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/24204136/friendly-id-4-using-scoped-module

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!