16

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

我想知道如何构建此代码以仅在联接中包含特定列。我不需要所有的用户信息。只是名字。有什么建议么。

当前代码:

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

2 回答 2

24

你可以使用这样的东西:

@comments = Comment.joins(:user)
                   .select("comments.*, users.first_name")
                   .where(study_id: @study.id)
于 2012-04-25T19:22:50.893 回答
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

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

于 2015-05-06T10:45:02.043 回答