Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 我可以使用阵列上的所有更新吗?_Ruby On Rails_Ruby - Fatal编程技术网

Ruby on rails 我可以使用阵列上的所有更新吗?

Ruby on rails 我可以使用阵列上的所有更新吗?,ruby-on-rails,ruby,Ruby On Rails,Ruby,我有一个数组中的注释列表。我可以使用阵列上的所有更新吗 comments = Comments.find(:all,:conditions => ["test is not null"]) comments.update_all(:test => nil) update_all是ActiveRecord提供的一种方法,您拥有的是一个数组,您有两个选项:通过注释使用ActiveRecord(将更新数据库)或映射数组,仅更改内存中的对象,而不修改数据库: comments = Co

我有一个数组中的注释列表。我可以使用阵列上的所有更新吗

comments = Comments.find(:all,:conditions => ["test is not null"]) 

comments.update_all(:test => nil)

update_all是ActiveRecord提供的一种方法,您拥有的是一个数组,您有两个选项:通过注释使用ActiveRecord(将更新数据库)或映射数组,仅更改内存中的对象,而不修改数据库:

comments = Comments.update_all({:test => nil}, 'test IS NOT NULL')


编辑:第二个示例中的错误是c。test not c

不能对数组使用
update\u all
,只能对作用域使用
find
all
(在旧版本的Rails中)返回一个数组。相反:

comments = Comments.scoped(:conditions => "test IS NOT NULL")
comments.update_all(:test => nil)
在现代版本的Ruby/ActiveRecord上,您可以编写:

Comments.where.not(test: nil).update_all(test: nil)

你可以使用
Comments.update_all(“test=NULL”,“test不是NULL”)
而不是让我很快地问一下——你试过了吗?Rails控制台是一个很好的尝试这类事情的工具。您的第二个示例实际上并没有将更改保存到数据库(它需要
c.save
或其他东西),您将整个注释设置为
nil
,而不仅仅是
c.test
。我修复了设置整个注释的问题,关于不保存数据库中的更改,这已经在我的答案文本中了,问题并没有说这些更改应该应用于数据库还是仅应用于数组。。。这就是为什么我给出了两个解决方案
Comments.where.not(test: nil).update_all(test: nil)