Rails 3连接 - 仅选择某些列

Kyl*_*yle 14 ruby activerecord ruby-on-rails

以下是评论与用户之间的关系.每个评论都有一个用户,所以我在下面的代码中构建了一个联接.

我想知道如何构建此代码只包括连接中的特定列.我不需要所有用户信息.只是first_name.有什么建议.

现行代码:

@comments = Comment.where(:study_id => @study.id).joins(:user)
Run Code Online (Sandbox Code Playgroud)

Ald*_*uca 22

你可以使用这样的东西:

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

  • 在这里,联接的行为类似于内部联接。否则使用包括:User.includes(:comments).select(...) (2认同)

mah*_*off 5

扩展 Aldo 的答案以显示一种检索生成的外部列值的方法。

@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
Run Code Online (Sandbox Code Playgroud)

您还可以users_first_name使用 attr_accessible 将注释声明为属性。我不认为有任何神奇的方法可以自动设置它,但是您可以在选择后循环中轻松地自己设置。