我有一个在此前提下运作的网站:
example.com/user_id/news/slug-for-article
默认情况下,我为文章启用了唯一的条目,但是我希望每个用户在所有用户中都具有唯一的条目。
使用来处理非唯一性@user.articles.friendly.find(param)
。
我该如何设置它以确保唯一性,但仅针对已定义的属性?
我会使用friendly_id。
它看起来像这样:
class Article < ActiveRecord::Base
extend FriendlyId
belongs_to :user
friendly_id :name, use: :scoped, scope: :user, slug_column: :permalink
如果有人选择相同的商品名称,friendly_id
则会计算出slug
与现有商品名称不冲突的商品名称。
因此,例如:
/user_id/news/hello
/user_id/news/hello-2
如果您不想使用该gem,则可以使用Rails
验证。
看起来像这样:
class Article < ActiveRecord::Base
extend FriendlyId
belongs_to :user
validates_uniqueness_of :permalink, scope: :user_id
希望对您有所帮助。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句