简体   繁体   中英

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.

Essentially it seems like Rails convention is to wrap attributes inside the name of a resource on POST and PUT calls. 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.create(content: params[:content])

Is there a Rails/Rubyist/API reason why the above is not recommended?

Rails form helpers usually wrap object attributes in an array named from the object and available in the 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.

Do:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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