2012-04-25 55 views
13

下面是注释和用户之间的关系。每条评论都有一个用户,所以我在下面的代码中构建了一个连接。导轨3连接 - 仅选择某些列

我想知道如何构建这个代码来只包含连接中的特定列。我不需要所有的用户信息。只是名字。有什么建议么。

目前代码:

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

您的评论模型没有:用户关联吗?你是否急于加载用户信息?你想用ActiveRecord尚未提供的连接来完成什么? – PinnyM 2012-04-25 19:11:39

+1

是的。我正在努力加载信息。目前,它为用户提供每个评论的用户。 – Kyle 2012-04-25 19:36:44

回答

21

你可以使用这样的事情:

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

这里连接的行为就像内连接一样。使用包括: User.includes(:评论).select(...) – 2013-12-04 10:07:05

3

扩展奥尔多的回答表现出的方​​法来检索得到的国外列值。

@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, e.g.: 
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作为与attr_accessible评论的ATTRIB。我不认为有任何神奇的方式来自动设置它,但你可以在后选择循环中轻松完成。

+1

美丽 - 这是它 – Yarin 2016-02-11 04:05:56

+0

这个工程。但要小心 - 当你检查输出时(实例'@ comments.first.inspect'或'@ comments.inspect'),你将看不到加入的数据,并且可能被误认为认为它无法实现。但是,当您指定“as”名称时,如本例中的“puts”所指定的那样 - 将显示出来。 – JosephK 2016-03-24 07:14:56

+0

好点,将它添加到示例中 – mahemoff 2016-03-24 17:28:11