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
You could use something like this:
@comments = Comment.joins(:user)
.select("comments.*, users.first_name")
.where(study_id: @study.id)
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.