Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
290 views
in Technique[技术] by (71.8m points)

associations - Need data from rails join table, has_many :through

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...