简体   繁体   中英

Virtual Attribute is nil when saving via accepts_nested_attributes_for

When I save a record through nested attributes, the virtual attribute doesn't get set in the child model.

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

Your code:

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

fetches the first associated House . Person has no way to know if you change it's house. You just overestimated the magic, I guess. All you need is to update_attributes of the house:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM