Activerecord 百货商店模式中的Rails嵌套属性不自动保存外键

Activerecord 百货商店模式中的Rails嵌套属性不自动保存外键,activerecord,ruby-on-rails-3.2,Activerecord,Ruby On Rails 3.2,在以下百货公司模式中,我有三种型号: class Store has_many :items, inverse_of: :store, autosave: true has_many :departments, inverse_of: :store, autosave: true accepts_nested_attributes_for :departments, allow_destroy: true class Department belongs_to :store,

在以下百货公司模式中,我有三种型号:

class Store
  has_many :items, inverse_of: :store, autosave: true
  has_many :departments, inverse_of: :store, autosave: true
  accepts_nested_attributes_for :departments, allow_destroy: true

class Department
  belongs_to :store, inverse_of: :departments
  has_many :items, autosave: true, inverse_of: department
  accepts_nested_attributes_for :items, allow_destroy: true

class Item
  belongs_to :store, inverse_of: :items
  belongs_to :department, inverse_of: :items
当我尝试以下方法时:

store = Store.new
department = store.departments.build
item = department.items.build

store.save
则该项目与该商店不关联

我的解决方案是将以下内容添加到项目模型中:

class Item
  before_validation :capture_store_info
  def capture_store_info
    self.store = self.department.store
  end
我将其添加到before_validation回调中,因为在我的非平凡代码中,我有一系列验证,包括检查存储模型是否存在的验证

问题:我的解决方案可行,但它是解决这个问题的正确的ie.Rails常规方法吗?有更好的解决办法吗。这感觉有点脏,每次我在Rails中做了一些感觉有点脏的事情,它都会回来咬我

谢谢, JB