Rails 3 Joins — Select only certain columns

后端 未结 2 1220
情话喂你
情话喂你 2020-12-30 03:59

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

相关标签:
2条回答
  • 2020-12-30 04:32

    You could use something like this:

    @comments = Comment.joins(:user)
                       .select("comments.*, users.first_name")
                       .where(study_id: @study.id)
    
    0 讨论(0)
  • 2020-12-30 04:53

    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.

    0 讨论(0)
提交回复
热议问题