【问题标题】:Rails activerecord deep eager loadingRails activerecord 深度急切加载
【发布时间】:2015-11-01 23:57:41
【问题描述】:

这是我的模型:

class User < ActiveRecord::Base
  has_many :products
  has_many :comments
end

class Product < ActiveRecord::Base
  belongs_to :user
  has_many :comments
end

class Comment < ActiveRecord::Base
  belongs_to :user
  belongs_to :product
end

我需要从当前用户 产品获取评论记录> 仅限

我该怎么做?谢谢

【问题讨论】:

    标签: ruby-on-rails ruby activerecord


    【解决方案1】:

    如果我们将关系移动到使用has_many: comments, through: products,您可能会得到您想要的:

    class User < ActiveRecord::Base
      has_many :products
      has_many :comments, through: products
    end
    
    class Product < ActiveRecord::Base
      belongs_to :user
      has_many :comments
    end
    
    class Comment < ActiveRecord::Base
      belongs_to :user
      belongs_to :product
    end
    

    现在你可以user.comments

    rails 文档是 here,上面写着:

    has_many :through 关联通常用于建立多对多 与另一个模型的连接。这种关联表明 声明模型可以与另一个的零个或多个实例匹配 通过第三种模型进行建模。例如,考虑一个 患者预约看医生的医疗实践。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多