Is a has_many through relationship possible with 4 models in rails?

不打扰是莪最后的温柔 提交于 2019-12-01 14:33:34

To answer your question: Yes, that's possible:

class A
  has_many :bs
  has_many :cs, through: :bs
  has_many :ds, through: :cs
end

class B
  has_many :cs
  belongs_to :a
end

class C
  has_many :ds
  belongs_to :b
end

class D
  belongs_to :c
end

If th association on A is named differently than the association on B, you need to supply the source parameter to the through-relation, like this:

class A
  has_many :bs
  has_many :cs, through: :bs, source: :ccs
end

class B
  has_many :cs, as: :ccs
  belongs_to :a
end

class C
  belongs_to :b
end

This will allow you to:

A.find(1).bs # => collection of B-instances
A.find(1).cs # => collection of C-instances

I'm not sure, if this answers your question. I hope so, but I'm a little confused about your example, so if not, please do comment :)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!