Search code examples
ruby-on-railsroutesslug

ruby on rails myprofile page


I want to create a profile page for users that signing up so let's say a user already registered, his profile link should be

website.com/profile/username

and on the views/profile/index.html.erb each user should see his own profile and edit it with the form_for I guess

so far I have profiles_controller.rb, profile.rb model and resources :profilesfor my routes.rb

What is the best way to do that?


Solution

  • If you wanna get by username then you need to use slug. The example below is for id version.

    Profile controller

    def show
       @profile = Profile.find(params[:id])
    end
    

    routes:

    get 'profile/:id' => 'profile#show'
    

    for :slug version, url will be like this: http://localhost:3000/profiles/**username**

    routes:

    resources :profiles, param: :slug
    

    profiles_controller

    def show 
    end
    
    private
    
    def set_profile
      @profile = Profile.find_by_username(params[:slug])
    end
    

    Or you can use gem for this https://github.com/norman/friendly_id