Rails 3的连接 - 只选择某些列 [英] Rails 3 Joins -- Select only certain columns

查看:139
本文介绍了Rails 3的连接 - 只选择某些列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是评论和用户之间的关系。每个注释都有一个用户,所以我建立了一个连接在下面的code。

我不知道如何构建这个code,其中只包含了加入某些特定的列。我并不需要所有的用户信息。就在FIRST_NAME。任何建议。

目前的code:

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

解决方案

您可以使用这样的:

  @comments = Comment.joins(:用户)
                   。选择(评论。*,users.first_name)
                   。凡(study_id:@ study.id)
 

Below is a relationship between Comments and a user. Each comment has one user so I'm building out a join in the code below.

I was wondering how to build this code to only include specific columns in the join. I don't need all of the user information. Just the first_name. Any suggestions.

Current Code:

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

解决方案

You could use something like this:

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

这篇关于Rails 3的连接 - 只选择某些列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆