更改关联对象不会使用rails模型对象保存?

时间:2011-12-18 22:58:48

标签: activerecord ruby-on-rails-3.1

拥有示例rails模型类的代码块:

class Block < ActiveRecord::Base
  has_many :bricks, :autosave => true
  def crunch
    bricks.each do |brick|
      if brick.some_condition?
        brick.name = 'New data'
        brick.save # why do I have to call this?
      end
    end 
  end
end
class Brick < ActiveRecord::Base
  belongs_to :block, :autosave => true
end

我发现确保相关对象中的更改为我保存的唯一方法是手动调用brick.save。甚至以为我使用:autosave => true

为什么?

2 个答案:

答案 0 :(得分:0)

自动保存选项可能具有误导性名称。顺便说一句,这是预期的行为。该选项用于关联。因此,如果您修改关系中的对象并保存其他对象,则 ActiveRecord会保存修改后的对象。因此,在您的情况下,您可以将代码更改为:

  def crunch
    bricks.each do |brick|
      if brick.some_condition?
        brick.name = 'New data'
      end
    end
    save # saving the father with autosave should save the children
  end

答案 1 :(得分:0)

您可以使用任何可用的辅助方法:update_attributeupdate_attributesupdate_column ......

更多信息:Rails: update_attribute vs update_attributes

相关问题