Question

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-sparo where 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
Était-ce utile?

La solution

I reckon this works:

# change in config/routes.rb
get '/profile/:id(/:username)' => 'profiles#show', :as => :profile

# change in app/controllers/profile_controller.rb
@user= User.find(params[:id])

# add to app/models/user.rb
def to_param
  "#{id}/#{username}"
end

Where username is whatever friendly_id uses to generate the slug

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top