开发者

Is the rails update controller method expected to be for one object only?

I often use ajax to update or delete objects in the controller. Now, there are the update and destroy methods, which generally look for a single id and perform actions on it. But I often need to to perform the same action to multiple objects. I can modify the update method to grab ids as an array and loop through them, to where whether it's one id or several, it will perform the same act开发者_如何学Goion to each - or create a nearly identical method for update_all. Is it wise to try to use update as an update_all method, or is it confusing? The downside of an update_all method seems like it would be very similar code, but done for all.

Is update in the controller expected to always be for one object? What are best practices and what do people normally do?


I prefer not to drastically alter the conceptual behavior of the 7 "out of the box" actions. If someone else comes along and tries to work in that code they will likely be confused as to why you changed it from the normal/usual update action behavior. Instead I would add a collection route named descriptively (update_many or something like that).

Also, can you abstract out the common code to dry things out?


You can call update on an ActiveRecord::Relation (the result of a lookup) and it will update all of the objects. Under the hood this is basically a convenience method that does the loop you described and calls update on each object. (See: the docs)

There's also an update_all method that works similarly to delete in that it just sends the query to the database. This will update all of the records with one query. However, this does not execute any of the rails validations or callbacks. In practice this severely limits the usefulness of this method for day to day coding. I've found this method more useful for bulk activities in special scripts.

Some commentary:

One of the downsides to Rails and ActiveRecord specifically is that its callback model is based around single record interactions with the database. While this makings coding incredibly wonderful, it makes large batch transactions really heavy. I've personally spent a lot of time working through (or around) this drawback. In the large, it's worth it for the other benefits.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜