Hide user id in the url bar

前端 未结 1 1849
没有蜡笔的小新
没有蜡笔的小新 2020-12-31 19:53

In my rails application I currently have a load of users who each have a registered user id.

If I go in to my users index and click on a users show page I get the fo

相关标签:
1条回答
  • 2020-12-31 20:15

    You can define a to_param method on the User model.

    class User
      ...
      def to_param
        name
      end
      ...
    end
    

    Then every generated URLs will have name instead of id as a user identifier.

    sid = User.new :name => 'sid'
    user_path(sid) #=> "/users/sid"
    

    Of course, in the controller, you have to find user by name.

    class UsersController
      ...
      def show
        @user = User.find_by_name(params[:id])
      end
      ...
    end
    

    I also suggest you to take a look at friendly_id gem.

    FriendlyId is the “Swiss Army bulldozer” of slugging and permalink plugins for ActiveRecord. It allows you to create pretty URL’s and work with human-friendly strings as if they were numeric ids for ActiveRecord models.

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