AnA*_*ice 23 ruby-on-rails ruby-on-rails-3
如何在控制台中将表Notification.email更新为all?
在控制台中,我想循环遍历表中的所有记录并设置email = true.
想法?
cbr*_*ron 37
这应该工作
Notification.all.each do |n| n.update_attribute(:email, true); end
Run Code Online (Sandbox Code Playgroud)
编辑:从bricker定制:
Notification.all.each { |n| n.update_attribute(:email, true) }
Run Code Online (Sandbox Code Playgroud)
m.s*_*tov 13
您可以使用:
Notification.update_all(email: true)
Run Code Online (Sandbox Code Playgroud)
如果您在更新时另外有条件,则应使用:
Notification.find_each { |n| n.email = (n.id > 100) ? true : false }
Run Code Online (Sandbox Code Playgroud)
Something.all对于庞大的db表,使用是个坏主意.
Notification.update_all(email: true)
Run Code Online (Sandbox Code Playgroud)
是基本答案.
您不必通过编写自己的块来"循环":您可以让活动记录为您完成繁重的工作 - 这里有一个ID数组的例子,您想要更新他们的电子邮件(我基本上直接从我的一个控制器拿到这个例子):
@notifications = Notification.where(id: [1,2,3,4,5,6]).update_all(email: true)
Run Code Online (Sandbox Code Playgroud)
编辑:大家注意sql注入不要在你的"where"方法中包含params [:notification_ids],原始字符串没有转义,否则你将遭受sql注入攻击; 或者是安全的并使用哈希.
| 归档时间: |
|
| 查看次数: |
26673 次 |
| 最近记录: |