Rails route to username instead of id

后端 未结 4 1571
情书的邮戳
情书的邮戳 2020-12-05 05:07

I am trying to change the rails routes from /users/1 to /username. I currently set this up so it works for the actions of showing and editing. The actual issue is that when

相关标签:
4条回答
  • 2020-12-05 05:34

    You can use friendly_id gem: https://github.com/norman/friendly_id

    0 讨论(0)
  • 2020-12-05 05:37

    In your user model:

    def to_param
      username
    end
    

    The to_param method on ActiveRecord objects uses, by default, just the ID of the object. By putting this code in your model, you're overwriting the ActiveRecord default, so when you link to a User, it will use the username for the parameter instead of id.

    0 讨论(0)
  • 2020-12-05 05:53

    You don't have to override to_param if you don't want to, you can just specify in the form tag like this:

    <%= form_for @user, :url => user_path(:id => @user.username) do |f|%>
    
    0 讨论(0)
  • 2020-12-05 05:56

    In the User model override the to_param method to return what you want used in the URL.

    class User < ActiveRecord::Base
      def to_param
        username
      end
    end
    

    In your controller instead of using User.find(params[:id]) you now need to use User.find_by_username(params[:id])

    0 讨论(0)
提交回复
热议问题