Search code examples
ruby-on-railsurlslugfriendly-id

friendly_id scope unique to parent resource


Is it possible to scope the slug to the parent resource so that two users can share the same resource slug? example:

two users would have news articles "i-am-awesome"

domain/joe/news/i-am-awesome domain/sara/news/i-am-awesome

I've made a custom validation for the slug for uniquiness on user's resource, but this still ends up generating a UUID for the second user. ends up being:

domain/sara/news/i-am-awesome-UUID


Solution

  • Might be too late to help, but yes, you can scope friendly_id. From the documentation:

    class Restaurant < ActiveRecord::Base
      extend FriendlyId
      belongs_to :city
      friendly_id :name, :use => :scoped, :scope => :city
    end
    
    class City < ActiveRecord::Base
      extend FriendlyId
      has_many :restaurants
      friendly_id :name, :use => :slugged
    end
    
    City.friendly.find("seattle").restaurants.friendly.find("joes-diner")
    City.friendly.find("chicago").restaurants.friendly.find("joes-diner")