有没有更简单的方法来返回活动记录结果集的belongs_to关系



我有两个模型:

Answers:
  belongs_to: user
User:
  has_many: answers

在Ruby或Rails中,有没有办法一次性执行以下操作,而不是创建一个数组并将所需的对象推送到其中?

def top_experts
    answers = Answer.where(some constraints)
    users = []
    answers.each do |answer|
        users << answer.user
    end
    users
end

您可以用户joins

def top_experts
    Answer.where(some constraints).includes(:user).collect{|x| x.user}
    # Will return an Array of users
end

编辑:

使用 includes 进行预先加载。它将减少为获取用户而执行的查询数量。

嗨,

您可以使用 select 子句来选择应与 where 子句一起返回的内容

Vote.select(user_id).where(some contraints)

使用子查询获取用户:

User.where( :id => Answer.where(some constraints).select(:user_id) )

参考:活动记录中的子查询

最新更新