开发者

Updating several model instances at the same time, The Rails Way?

开发者 https://www.devze.com 2023-01-11 12:26 出处:网络
I have a settings table with two fields, key and value. Now, while creating an administration secti开发者_运维技巧on for it I want to be able to edit all settings at once.

I have a settings table with two fields, key and value. Now, while creating an administration secti开发者_运维技巧on for it I want to be able to edit all settings at once.

Is there a "Rails (3) way" to do this that will save me some time?


ActiveRecord has an update_all method for updating all the records with the specified string of column and value pairs that match the usual conditions etc. that find supports. The method issues a single SQL UPDATE statement behind the scenes.

For example:

Setting.update_all("key = 'foo', value = 'bar'")

—equates to:

UPDATE settings SET key='foo', value='bar';
  • update_all API documentation

If you want to perform a mass update of multiple settings with different key/value values then there are a couple of Railscasts that cover how to do this:

  • Episode #165: Edit Multiple
  • Episode #198: Edit Multiple Individually
0

精彩评论

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