需要来自rails join table的数据,has_many:through

时间:2012-01-16 00:42:28

标签: ruby-on-rails associations has-many-through has-many

我有3个表 - 用户,事物和以下内容。用户可以通过下表跟踪事项,将user_idthings_id相关联。这意味着:

class User
  has_many :things, :through => :follows
end

class Thing
  has_many :users, :through => :follows
end

class Follow
  belongs_to :users
  belongs_to :things
end

所以我可以毫无问题地检索thing.users。我的问题是如果在下面的表中,我有一个名为“relation”的列,所以我可以将一个关注者设置为“admin”,我希望能够访问该关系。所以在循环中我可以做类似的事情:

<% things.users.each do |user| %>
  <%= user.relation %>
<% end %>

有没有办法将关系包含在原始用户对象中?我尝试了:select => "follows.relation",但似乎没有加入该属性。

3 个答案:

答案 0 :(得分:22)

要执行此操作,您需要在has_many中使用一些SQL。这样的事情应该会有所作为。 has_many :users, :through => :follows, :select => 'users.*, follows.is_admin as is_follow_admin'

然后在循环中你应该有权访问 user.is_follow_admin

答案 1 :(得分:8)

对于使用rails 4的人,不推荐使用:order,:select等。现在您需要指定如下:

has_many :users, -> { select 'users.*, follows.is_admin as is_follow_admin' }, :through => :follows

答案 2 :(得分:0)

您可以执行以下操作:

<% things.follows.each do |follow| %>
  <%= follow.relation %>
  <%= follow.user %>
<% end %>
相关问题