Question

First I am sorry for my English

I am using Friendly_id gem to create Clean URL and it work just fine but instead of having a URL like this http://localhost:3000/profile/jack-sparo I want a URL like this http://localhost:3000/profile/1/jack-sparowhere 1 is the user_id, so how can I do it?

this is my config/routes

  get "profiles/show" 

  get '/profile/:id' => 'profiles#show', :as => :profile
  get 'profiles' => 'profiles#index'

and this is my Profile controller

  def show
    @user= User.find_by_slug(params[:id])
    if @user
        @posts= Post.all
        render action: :show
    else
        render file: 'public/404', status: 404, formats: [:html]
    end
  end

No correct solution

OTHER TIPS

If you have an id of the record in URL anyway, you don't need Friendly_id gem. You need to tune routes.

But maybe you would be happy with something like this instead?

http://localhost:3000/profiles/1-john-smith

If so, you need to override to_param method in User model like this:

class User < ActiveRecord::Base
  def to_param
    "#{id}-#{name}".parameterize
  end
end

Now the profile_path(profile) helper will generate URL like

http://localhost:3000/profiles/1-john-smith

And, with this request, the User.find(params[:id]) in controller will find profile with id 1 and cut all other stuff which was in URL.

So

http://localhost:3000/profiles/1-mojombo-smith

will link to the same profile as

http://localhost:3000/profiles/1-john-smith
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top