繁体   English   中英

Rails-如何通过自己的标准(而非ID)设置行动路径

[英]Rails - how to set up path to action by own criteria (not ID)

当我有这样的路径时:

user_messages_path(current_user)

它生成以下URL:

users/1/listings

我存储在数据库用户的唯一代码中,所以我不想显示类似

users/ID/listings

但更像

users/CODE/listings

我如何更新使用带有用户代码的路径的路由?

谢谢

user_messages_path(current_user)

是以下操作的快捷方式:

user_messages_path(current_user.to_param)

通常这样做:

user_messages_path(current_user.id)

您可以:

  • 传递您想要的任何字符串: user_messages_path('foo')

  • 或在模型中覆盖to_param

只是要注意更新负责从参数中检索对象的代码。

user.rb

def to_param
  uuid        # or whatever attribute you want to use instead of the id
end

在控制器中,而不是User.find(params[:id])

User.find_by_uuid!(params[:id]) # adjust to the attribute name used in to_param 

您可以使用自定义路由,如下所示。

get 'users/:code/:listings' => 'listings#index', as: :user_messages

然后在您的params中,键:code将返回网址的那部分,例如params [:code]在您的控制器中,您可以使用以下命令

Rails 3.2

 User.find_by_code(params[:code])

滑轨4

User.where(code: params[:code])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM