简体   繁体   English

Rails REST API POST 参数

[英]Rails REST API POST params

I'm building a RESTful (or mostly RESTful...) API using Rails and have a simple question that I have been strugging to find an answer to.我正在使用 Rails 构建一个 RESTful(或主要是 RESTful...)API,并且有一个我一直在努力寻找答案的简单问题。

Essentially it seems like Rails convention is to wrap attributes inside the name of a resource on POST and PUT calls.从本质上讲,似乎 Rails 约定是在 POST 和 PUT 调用上将属性包装在资源的名称中。 What I mean is usually you create or update an object in the following manner inside a controller:我的意思是通常您在控制器内以以下方式创建或更新对象:

Object.create(params[:object])

or或者

Object.update_attributes(params[:object])

My question is;我的问题是; is there a reason for this?是否有一个原因? If I have a simple class, say a Comment class, that has only a content attribute, I could have the following如果我有一个简单的类,比如说一个 Comment 类,它只有一个内容属性,我可以有以下内容

Comment.create(content: params[:content])

Is there a Rails/Rubyist/API reason why the above is not recommended?是否有 Rails/Rubyist/API 原因不推荐上述内容?

Rails form helpers usually wrap object attributes in an array named from the object and available in the params. Rails 表单助手通常将对象属性包装在从对象命名的数组中,并在 params 中可用。

You can decide to format your params differently, that's up to yo, just avoid naming collisions.你可以决定以不同的方式格式化你的参数,这取决于你,只是避免命名冲突。

As for: Comment.create(params[:content]) will not work.至于: Comment.create(params[:content])将不起作用。

Do:做:

Comment.create(content: params[:content])

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

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