委托协会

时间:2018-09-18 13:09:59

标签: ruby-on-rails

我有一个模型A,该模型具有许多其他模型B,而模型B具有多个第三模型C,并且想要将A从B委派给C。例如:

class House < ApplicationRecord
  has_many :pets
end

class Pet < ApplicationRecord
  belongs_to :house
  has_many :toys
  delegate :house, to: :toys
end

class Toy < ApplicationRecord
  belongs_to :pet
end

> toy.house

按现状,我必须使用toy.pet.house

2 个答案:

答案 0 :(得分:2)

尝试

class Toy < ApplicationRecord
  belongs_to :pet 
  delegate :house, to: :pet 
end

然后删除

delegate :house, to: :toys 

来自Pet

至少有两个问题:

class Pet < ApplicationRecord
  belongs_to :house
  has_many :toys
  delegate :house, to: :toys
end

首先,Toy的实例不响应house,因此您无法delegate :house, to: :toys。其次,即使Toy did 的实例响应house,您也将无法在集合上调用该实例方法,这就是{{1} }是。所以,到处都是。

toys,但是确实响应Pet。并且,house。因此,您进行了Toy belongs_to :pet。而鲍勃是你的叔叔!

答案 1 :(得分:0)

您可以在ActiveRecord关联上使用:through选项来完成所需的操作。如下配置模型:

class House < ApplicationRecord
  has_many :pets
  has_many :toys, through: :pets
end

class Pet < ApplicationRecord
  belongs_to :house
  has_many :toys
end

class Toy < ApplicationRecord
  belongs_to :pet
  has_one :house, through: :pet
end

这里是:through option的has_many和has_one关联的官方指南的链接。