Rails 3连接 – 仅选择某些列

以下是评论与用户之间的关系。 每个评论都有一个用户,所以我在下面的代码中构建了一个联接。

我想知道如何构建此代码只包括连接中的特定列。 我不需要所有用户信息。 只是first_name。 有什么建议。

现行代码:

@comments = Comment.where(:study_id => @study.id).joins(:user) 

你可以使用这样的东西:

 @comments = Comment.joins(:user) .select("comments.*, users.first_name") .where(study_id: @study.id) 

扩展Aldo的答案以显示检索结果外部列值的方法。

 @comments = \ Comment\ .joins(:user) .select("comments.*, users.first_name as users_first_name") .where(study_id: @study.id) # Now it's stored on each comment as an attribute, eg: puts @comments.first.read_attribute(:users_first_name) puts @comments.first.attributes['users_first_name'] # Note that inspecting the comment won't show the foreign data puts @comments.first.inspect # you won't see user's first name output 

您还可以使用users_first_name声明为注释的attrib。 我不认为有任何神奇的方法可以自动设置它,但你可以在后选择循环中自己轻松完成。