13

I have 3 tables - users, things, and follows. Users can follow things through the follows table, associating a user_id with a things_id. This would mean:

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

So I can retrieve thing.users with no problem. My issue is if in the follows table, I have a column named "relation", so I can set a follower as an "admin", I want to have access to that relation. So in a loop I can do something like:

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

Is there a way to include relation into the original user object? I have tried :select => "follows.relation", but it doesn't seem to join the attribute.

jvperrin
  • 3,368
  • 1
  • 23
  • 33
Matt Gaidica
  • 554
  • 5
  • 14

3 Answers3

22

To do this you need to use a bit of SQL in the has_many. Something like this should hopefully work. has_many :users, :through => :follows, :select => 'users.*, follows.is_admin as is_follow_admin'

Then in the loop you should have access to user.is_follow_admin

Bradley Priest
  • 7,438
  • 1
  • 29
  • 33
  • Definitely works, and is essentially what I was trying before. My hangup was that the SQL dump when doing this on the command line doesn't show the is_admin attribute anywhere.. it just shows the follows object. Thank you! – Matt Gaidica Jan 16 '12 at 01:20
  • 2
    Rails4 deprecated :select I think. How is this accomplished now? – index Jul 25 '13 at 07:26
  • 8
    I'm using rails 4 and this format works `has_many :users, -> { select('users.*, members.role as member_role') }, through: :members` – index Dec 11 '13 at 06:51
  • @Matt Gaidica, you should add this to your User model (to make attribute accessible) - `def is_follow_admin attributes['is_follow_admin'] end` – Richard Peck Dec 30 '13 at 18:35
8

For people using rails 4, the usage of :order, :select, etc has been deprecated. Now you need to specify as follows:

has_many :users, -> { select 'users.*, follows.is_admin as is_follow_admin' }, :through => :follows
Seoman
  • 783
  • 1
  • 7
  • 18
0

You might be able to do something like:

<% things.follows.each do |follow| %>
  <%= follow.relation %>
  <%= follow.user %>
<% end %>
jvperrin
  • 3,368
  • 1
  • 23
  • 33
Johnny Brown
  • 1,000
  • 11
  • 18