0
當我通過嵌套屬性保存記錄時,虛擬屬性不會在子模型中設置。虛擬屬性在保存時爲零通過accep_nested_attributes_for
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
確實有道理。如果保存一個params散列,它會是一樣的嗎?即 - @ person.update_attributes(params [:person]) – 2012-04-11 17:39:49
'house_name:'瘋狂屋'是一個'哈希',所以你可以自由地提供你自己的。 – jdoe 2012-04-11 17:42:05
正確,但多數民衆贊成在一個哈希更新只是房子,而不是通過父對象,這是我想要的理想.. – 2012-04-11 18:07:49