2012-04-11 45 views
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 

回答

0

您的代碼:

person.houses.first.house_name = 'crazy house' 

獲取的第一個關聯HousePerson無法知道你是否改變它的房子。我想,你只是高估了魔法。所有你需要的是房子的update_attributes

person.houses.first.update_attributes house_name: 'crazy house' 
+0

確實有道理。如果保存一個params散列,它會是一樣的嗎?即 - @ person.update_attributes(params [:person]) – 2012-04-11 17:39:49

+0

'house_name:'瘋狂屋'是一個'哈希',所以你可以自由地提供你自己的。 – jdoe 2012-04-11 17:42:05

+0

正確,但多數民衆贊成在一個哈希更新只是房子,而不是通過父對象,這是我想要的理想.. – 2012-04-11 18:07:49