【问题标题】:Rails Activerecord query selective includeRails Activerecord 查询选择性包括
【发布时间】:2013-08-16 21:57:47
【问题描述】:

我在优化大型活动记录查询时遇到问题。我需要在我的请求中包含一个关联模型,但由于返回集的大小,我只想包含几个关联列。例如我有:

Post.includes(:user).large_set

当我在寻找类似的东西时:

Post.includes(:user.name, :user.profile_pic).large_set

据我所知,我需要实际使用名称和个人资料图片属性,因此 Post.joins(:user) 不是一个选项。

【问题讨论】:

    标签: sql ruby-on-rails ruby rails-activerecord


    【解决方案1】:

    select 就是你要找的东西:

    Post.select("posts.*, users.name, users.profile_pic").large_set
    

    http://guides.rubyonrails.org/active_record_querying.html#selecting-specific-fields

    【讨论】:

    • 这不是我想要的,但你说得对,我需要 select 方法,所以我会接受这个答案。从技术上讲,您的电话包括整个用户模型,这是我试图避免的。最小的调用是 Post.select("posts.*, users.name, users.profile_pic").large_set
    • 不客气。我更新了答案以匹配对您有用的答案。
    【解决方案2】:

    你必须使用 join 来完成你想要的,因为 include 没有这个功能。或者你可以白你自己的包含方法:-)

    【讨论】:

      猜你喜欢
      • 2019-08-04
      • 1970-01-01
      • 2011-06-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多