Search code examples
ruby-on-railsrubyurlmethodsfriendly-id

Creating a FriendlyId with a one-to-many relationship


I have a User model that has a has_many relationship with a Post model.

Class User < ActiveRecord::Base
  has_many :posts
end

Class Post < ActiveRecord::Base
  attr_accessor :user_id

  belongs_to :user
end

I'd like to setup the url of my post model where the name of the post's owner goes first followed by the name of the post:

localhost:3000/john/sample-post

I tried setting this up in my slug_candidates method inside my post model but got errors:

Class Post < ActiveRecord::Base
  ...
  extend FriendlyId
  friendly_id :slug_candidates, user: [:slugged, :history]

  def slug_candidates
    [:name, [self.user.name, :name]]
  end
end

What would I need to change in this method to get it to work?


Solution

  • The docs explain this with the following example:

    You can prefix routes with a named parameter also:

    scope ':username' do
      resources :posts
    end
    

    This will provide you with URLs such as /bob/posts/1 and will allow you to reference the username part of the path as params[:username] in controllers, helpers and views.