Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3 Joins -- Select only certain columns

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)
like image 885
Kyle Avatar asked Apr 25 '12 19:04

Kyle


2 Answers

You could use something like this:

@comments = Comment.joins(:user)
                   .select("comments.*, users.first_name")
                   .where(study_id: @study.id)
like image 70
Aldo 'xoen' Giambelluca Avatar answered Nov 04 '22 09:11

Aldo 'xoen' Giambelluca


Extending Aldo's answer to show a way to retrieve the resulting foreign column value.

@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

You could also declare users_first_name as an attrib on the comment with attr_accessible. I don't think there's any magic way to automatically set it, but you could easily do so yourself in a post-select loop.

like image 20
mahemoff Avatar answered Nov 04 '22 09:11

mahemoff