Ruby-on-rails 在 Rails 控制台中。如何更新所有记录的字段?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7693127/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 02:07:33  来源:igfitidea点击:

In Rails Console. how to update a field for all records?

ruby-on-railsruby-on-rails-3

提问by AnApprentice

how can I update a table Notification.email to all true in console?

如何在控制台中将表 Notification.email 更新为全部 true?

In console, I'd like to loop through all the records in the table and set email = true.

在控制台中,我想遍历表中的所有记录并设置 email = true。

Ideas?

想法?

回答by cbron

this should work

这应该有效

Notification.all.each do |n| n.update_attribute(:email, true); end

edit: made custom from bricker:

编辑:从砖家定制:

Notification.all.each { |n| n.update_attribute(:email, true) }

回答by apneadiving

You're looking for update_all. See doc.

您正在寻找update_all. 见文档

Beware, no callbacks are triggered this way.

请注意,不会以这种方式触发回调。

回答by user3767658

You can use:

您可以使用:

Notification.update_all(email: true)

If you additionally have a condition while updating you should use:

如果您在更新时还有条件,则应使用:

Notification.find_each { |n| n.email = (n.id > 100) ? true : false }

Use Something.allis bad idea for huge db table.

使用Something.all巨大的数据库表是个坏主意。

回答by BKSpurgeon

Notification.update_all(email: true) 

is the basic answer.

是基本答案。

You don't have to "loop through" per se by writing your own block: you can let active record do the hard work for you - here is an example of where you have an array of ids and you want to update their emails (i basically took this example straight from one of my controllers):

您不必通过编写自己的块来“循环”本身:您可以让活动记录为您完成繁重的工作 - 这是您拥有一组 id 并且您想要更新他们的电子邮件的示例(我基本上直接从我的一个控制器中获取了这个示例):

@notifications = Notification.where(id: [1,2,3,4,5,6]).update_all(email: true)

Edit: folks watch out for sql injection do not include a params[:notification_ids]in your "where" method with a raw string, without escaping, or you will suffer sql injection attacks; or be safe and use a hash. If that doesn't make sense, please review the following: https://guides.rubyonrails.org/security.html#sql-injection

编辑:注意 sql 注入的人不要params[:notification_ids]在“where”方法中包含带有原始字符串的 a ,不要转义,否则您将遭受 sql 注入攻击;或者是安全的并使用哈希。如果这没有意义,请查看以下内容:https: //guides.rubyonrails.org/security.html#sql-injection