通过多个属性的模型的嵌套属性

时间:2015-10-19 19:49:04

标签: ruby-on-rails ruby associations

我有三种型号。

class Business < ActiveRecord::Base
  has_one :employee

  accepts_nested_attributes_for :employee
end

class Employee < ActiveRecord::Base
  has_one :slave

  belongs_to :business

  accepts_nested_attributes_for :slave
end

class Slave < ActiveRecord::Base
  belongs_to :employee
end

我有一些奴隶参数被发送到我的控制器来更新奴隶和商业记录。 slave params包含一个具有更新业务属性的密钥business_attributes。但是我不确定如何正确地连接它。

我应该在从属模型中添加accepts_nested_attributes_for以接受business_attributes吗?或者我是否需要将business_attributes包含在employee_attributes哈希中,并为accepts_nested_attributes_for设置员工模型business_attributes?任何有关这方面的帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

首先,如果您需要以这种方式传递数据,我会说您可能会过度复杂化您的结构或表单。您可以使用业务控制器使用您已有的关系来处理表单逻辑。

如果您确实需要将业务属性直接传递给从属服务器,则需要在从服务器和业务之间直接创建某种关系。类似的东西:

delegate :business, to: :employee
accepts_nested_attributes_for :business

*注意:这是未经测试的,如果您经常从服务器引用业务(n + 1个查询),则可能效率低下。