【问题标题】:Eager load only first associations with ActiveRecord急切加载仅与 ActiveRecord 的第一个关联
【发布时间】:2015-03-19 10:45:41
【问题描述】:

我有一个User 模型和一个:friends 关联

当我创建数据时,我会获取用户及其前 5 个朋友

我可以的

User.includes(:friends)

但这会带走所有的朋友。

有没有办法只带前 5 个朋友?

【问题讨论】:

    标签: ruby-on-rails-4 activerecord eager-loading


    【解决方案1】:

    我想以下方法可以工作:

    class User < ActiveRecord::Base
      has_many :friends
      has_many :top_friends, -> { limit(5).order(:id) }, class_name: Friend
    end
    
    User.includes(:top_friends) 
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-28
    • 2010-12-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多