Activerecord 更改关联对象不';无法使用rails模型对象保存?
具有示例rails模型类的以下代码块:Activerecord 更改关联对象不';无法使用rails模型对象保存?,activerecord,ruby-on-rails-3.1,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?
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
为什么?可能自动保存选项的名称有误导性。顺便说一下,这是预期的行为。该选项用于关联。因此,如果修改关系中的一个对象并保存另一个对象,则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
您可以使用任何可用的帮助器方法:
update\u attribute
,update\u attributes
,update\u column
更多信息:更好但不完美。。。但这似乎是大多数项目所做的