Need data from rails join table, has_many :through
Asked Answered
H

3

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.

Henke answered 16/1, 2012 at 0:42 Comment(2)
Its a really bad idea to name a relation "relation"... This may break some ruby internals and you will get unexpected behaviour!Grease
Alright, thanks. Lets say the column is named "is_admin" and has a type of boolean..Henke
P
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

Pershing answered 16/1, 2012 at 1:9 Comment(4)
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!Henke
Rails4 deprecated :select I think. How is this accomplished now?Alfano
I'm using rails 4 and this format works has_many :users, -> { select('users.*, members.role as member_role') }, through: :membersAlfano
@Matt Gaidica, you should add this to your User model (to make attribute accessible) - def is_follow_admin attributes['is_follow_admin'] endRenell
M
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
Marlonmarlow answered 3/11, 2014 at 7:42 Comment(0)
R
0

You might be able to do something like:

<% things.follows.each do |follow| %>
  <%= follow.relation %>
  <%= follow.user %>
<% end %>
Rosinweed answered 16/1, 2012 at 1:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.