-2

I'd like to write a quick method that can help me initialize a few fields in one of my ruby tables. This is what I have so far but it does not work. I would like to be able to feed an array of field names into this function so that I can get the whole initialization done in one loop.

fields =["field1","field2","field3","field4"]
tasks = Task.all

tasks.each do |task|
    fields.each do |field|
        if task.field.nil?
            task.update_attribute :field => true
        end
    end
end
4

3 回答 3

1

如果这实际上是 Rails,看起来是这样,您可以使用哈希访问:

task[field] = true if task[field].nil?

您仍然需要save修改后的记录。

您可以task.update_attribute(field, true)改用:这将立即更新数据库,但将为每个修改的属性执行事务。

于 2013-10-19T15:31:07.537 回答
1

也许这就是你的意思:

fields = %w[field1 field2 field3 field4]
tasks = Task.all

tasks.each do |task|
  fields.each do |field|
    task.update_attribute :"#{field}" => true if task.send(field).nil?
  end
end
于 2013-10-19T15:28:54.277 回答
1

尝试始终对数据库使用最少数量的查询

fields = ["field1","field2","field3","field4"]

fields.each do |field|
  Task.where({field => nil}).update_all({field => true})
end
于 2013-10-19T15:52:30.077 回答