如何在 Ruby on Rails 应用程序中处理 RESTful URL 参数?
我正在处理一个非常简单的 RESTful Rails 应用程序。有一个用户模型,我需要更新它。 Rails 编码员喜欢这样做:
if @user.update_attributes(params[:user])
...
根据我对 REST 的理解,这个 URL 请求应该可以工作:
curl -d "first_name=tony&last_name=something2&v=1.0&_method=put" http://localhost:3000/users/1.xml
但是,很明显,这是行不通的,因为每个 URL 参数将被解析为变量“params”而不是“params[:user]” “
我现在有一个黑客修复程序,但我想知道人们通常如何处理这个问题。
谢谢
I am dealing with a very simple RESTful Rails application. There is a User model and I need to update it. Rails coders like to do:
if @user.update_attributes(params[:user])
...
And from what I understand about REST, this URL request should work:
curl -d "first_name=tony&last_name=something2&v=1.0&_method=put" http://localhost:3000/users/1.xml
However, it's quite obvious that will not work because each URL parameter will be parsed to the variable "params" and not "params[:user]"
I have a hackish fix for now, but I wanted to know how people usually handle this.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这只是Rails 如何解析参数的问题。您可以使用方括号将参数嵌套在哈希中。像这样的东西应该可以工作:
这应该变成
你的
params
哈希值。这也是 Rails 表单助手构建 params 哈希的方式,它们在表单输入标记name
属性中使用方括号。It's just a matter of how Rails parses parameters. You can nest parameters in a hash using square brackets. Something like this should work:
This should turn into
in your
params
hash. This is how Rails form helpers build the params hash as well, they use the square brackets in the form input tagname
attribute.这是一个权衡;你可以有稍微丑陋的网址,但非常简单的控制器/模型。或者你可以有漂亮的网址但稍微丑陋的控制器/模型(用于进行参数的自定义解析)。
例如,您可以在您的用户模型上添加此方法:
现在在您的控制器上您可以执行以下操作:
这将很好地处理您的帖子,以及来自表单的帖子。
当我需要我的客户“复制并粘贴”网址时(即他们可以通过电子邮件发送的搜索),我通常会出现这种行为。
It's a tradeoff; You can have slightly ugly urls, but very simple controller/models. Or you can have nice urls but slightly ugly controller/models (for making custom parsing of parameters).
For example, you could add this method on your User model:
Now on your controller you can do this:
This will handle your post nicely, and also posts coming from forms.
I usually have this kind of behaviour when I need my clients to "copy and paste" urls around (i.e. on searches that they can send via email).