0

当我通过嵌套属性保存记录时,虚拟属性不会在子模型中设置。

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
4

1 回答 1

0

你的代码:

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

获取第一个关联的House. Person没有办法知道你是否改变它的房子。我猜你只是高估了魔法。所有你需要的是update_attributes房子:

person.houses.first.update_attributes house_name: 'crazy house'
于 2012-04-11T17:34:58.693 回答