当我通过嵌套属性保存记录时,虚拟属性不会在子模型中设置。
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