当我通过嵌套属性保存记录时,虚拟属性不会在子模型中设置。
class Person < ActiveRecord::Base
has_many :houses
accepts_nested_attributes_for :houses
end
class House < ActiveRecord::Base
attr_accessor :house_name #virtual
before_save do
puts attributes # doesn't include house_name when saving through parent model
puts @house_name # nil when saving through parent model
end
end
person = Person.find(1)
person.houses.count #=> 3
person.houses.first.house_name = 'crazy house'
person.save # house_name not in attributes
house = person.houses.first
house.house_name = 'moms house'
house.save #house_name is in attributes
答案 0 :(得分:0)
您的代码:
person.houses.first.house_name = 'crazy house'
获取第一个关联的House
。 Person
无法知道你是否改变了它的房子。我想你只是高估了魔法。你需要的只是房子的update_attributes
:
person.houses.first.update_attributes house_name: 'crazy house'