【问题标题】:Define a nested has_many and belongs_to定义一个嵌套的 has_many 和 belongs_to
【发布时间】:2019-01-23 19:26:43
【问题描述】:

假设我有 3 个模型,ABC(其中 A 有很多 BB 有很多 C):

class A < ActiveRecord::Base
  has_many :bs
end

class B < ActiveRecord::Base
  belongs_to :a
  has_many :cs
end

class C < ActiveRecord::Base
  belongs_to :b
end

所以这里一切正常。使用A.first.bs,我得到与A 的第一个实例相关联的B 的所有实例,使用C.last.b,我得到与C 的最后一个实例相关联的B 的实例,等等。

但是想能够做到A.first.csC.last.a,我该怎么做呢?

我想这样做是因为我希望能够做到C.all.joins(:a),因为我想绘制一些关于C 实例的统计数据,按A 分组。还有其他方法可以做到这一点吗?

【问题讨论】:

    标签: ruby-on-rails activerecord rails-activerecord activeadmin rails-models


    【解决方案1】:

    只需创建遍历树的indirect associations

    class A < ApplicationRecord
      has_many :bs
      has_many :cs, through: :bs
    end
    
    class B < ApplicationRecord
      belongs_to :a
      has_many :cs
    end
    
    class C < ApplicationRecord
      belongs_to :b
      has_one :a, through: :b
    end
    

    这会让你从两端出发:

    A.first.cs
    C.last.a 
    # etc
    

    ActiveRecord 会自动加入中间模型(B)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多