Reputation: 5957
I have a website that has works on the premise:
example.com/user_id/news/slug-for-article
By default, I have enabled unique slugs for articles, however I would like to have slugs unique per user, across all users.
The non-uniqueness is handled by using @user.articles.friendly.find(param)
.
How can I set this up so it ensures uniqueness, but only for a defined attribute?
Upvotes: 0
Views: 790
Reputation: 532
I would use friendly_id.
It would look like this:
class Article < ActiveRecord::Base
extend FriendlyId
belongs_to :user
friendly_id :name, use: :scoped, scope: :user, slug_column: :permalink
In case someone picks the same article name, friendly_id
will calculate a slug
that doesn't clash with an existing one.
So, for example:
/user_id/news/hello
/user_id/news/hello-2
If you don't want to use that gem, you can just use Rails
validations.
It'd look like this:
class Article < ActiveRecord::Base
extend FriendlyId
belongs_to :user
validates_uniqueness_of :permalink, scope: :user_id
Good old validates_uniqueness_of.
I hope it helps.
Upvotes: 4
Reputation: 36880
AIf you have a has_many through: association you could store the slug in the third model... it's the only place where you can store data unique to both the user and article.
@user.articles_users.friendly.find(param).each do |association|
Articles.find(association.article_id)
end
Upvotes: 1