Rails 路由到用户名而不是 id [英] Rails route to username instead of id

查看:29
本文介绍了Rails 路由到用户名而不是 id的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将 rails 路由从/users/1 更改为/username.我目前进行了设置,因此它适用于显示和编辑操作.实际问题是,当我使用以下方法更新用户时:

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 I go to update the user by using:

<%= form_for @user do |f|%>

它永远不会更新,因为更新操作被路由到/users/:id.有什么方法可以路由它以便它适用于/用户名?(这是在我的表单中作为动作呈现的路线).一段时间以来,我一直在为这个问题挠头.

It never updates, because the update action is routed to /users/:id. Is there any way to route this so that it works for /username? (which is the route that is rendering in my forms as the action). I've been scratching my head over this one for a while now.

问题不是路由到用户名,它工作正常.问题是表单路由到/username 进行更新,但是用户的更新路由仍然是/users/:id 而不是 :/id.

The issue isn't routing to username, that it working correctly. The issue is that the form routes to /username for update, however the update route for users is still /users/:id instead of :/id.

我尝试更新我的路线,但无济于事:

I tried updating my routes to this, but to no avail:

match '/:id', :to => "users#show", :as => :user
match '/:id', :to => "users#update", :as => :user, :via => :put
match '/:id', :to => "users#destroy", :as => :user, :via => :delete

哦!这解决了问题:

match '/:id', :to => "users#show", :as => :user, :via => :get

推荐答案

在您的用户模型中:

def to_param
  username
end

ActiveRecord 对象上的 to_param 方法默认使用对象的 ID.通过将此代码放入您的模型中,您将覆盖 ActiveRecord 默认值,因此当您链接到用户时,它将使用 username 作为参数而不是 id.

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.

这篇关于Rails 路由到用户名而不是 id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆