简体   繁体   English

通过accepts_nested_attributes_for保存时,虚拟属性为nil

[英]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 . 获取第一个关联的House Person has no way to know if you change it's house. Person无法知道您是否要更换房屋。 You just overestimated the magic, I guess. 我猜你只是高估了魔术。 All you need is to update_attributes of the house: 您需要做的只是更新房子的update_attributes

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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