开发者

Rails Route based on something different than ID

开发者 https://www.devze.com 2023-04-13 09:17 出处:网络
So currently I have something like /users/1/ when I want to view a user profile. How can I go through routes.r开发者_如何学编程b to change that to /user/chiggins/ where chiggins is a unique username?Y

So currently I have something like /users/1/ when I want to view a user profile. How can I go through routes.r开发者_如何学编程b to change that to /user/chiggins/ where chiggins is a unique username?


You need is to override to_param method in User model:

class User
  def to_param
   username
  end
end

Then rails will use it automagically for routing. See http://api.rubyonrails.org/classes/ActiveRecord/Base.html#method-i-to_param


Another possibility to consider would be the friendly_id gem - https://github.com/norman/friendly_id


Nowadays there is a :param argument on the resource declaration. http://guides.rubyonrails.org/routing.html#overriding-named-route-parameters


You can get per-resource identifier customization by redefining the member_scope and nested_scope methods on the Resource instance.

resources :users do
  @scope[:scope_level_resource].tap do |u|
    def u.member_scope
      "#{path}/:username"
    end

    def u.nested_scope
      "#{path}/:#{singular}_username"
      # member_scope also usable here, assuming username will be nowhere in nested routes.
    end
  end
end

Regarding the question about #nested_scope below: It gets used when you do something like this in routing:

resources :members do
  resources :playlists, only: :index
end

Then, the param would be :member_username instead of just :username. This is useful in the playlists controller when assembling the collection so you can infer the scope of the request.


The best way is to define a route with a custom param:

match "/users/:username" => "users#show"

In your controller, the plain old params[:id] will be params[:username], and you can get the user from de DB using:

User.find_by_username(params[:username])
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号