Question

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?

Was it helpful?

Solution

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:

  1. Article with id #1 named "Hello" would have permalink /user_id/news/hello
  2. Article with id #2 named also "Hello" would have permalink /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.

OTHER TIPS

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top