问题描述
我有3个表 - 用户,东西,如下。用户可以按照事情经过如下表,关联一个 USER_ID
与 things_id
。这意味着:
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
所以我可以检索没有问题thing.users。我的问题是,如果在如下表,我有一个名为关系一栏,这样我就可以设置一个跟随者为管理员,我想有机会获得这层关系。因此,在一个循环中我可以这样做:
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 %>
有没有一种方法,包括关系到原来的用户对象?我曾尝试:选择=&GT; follows.relation
,但它似乎并没有加入该属性。
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.
推荐答案
要做到这一点,你需要使用一个位SQL中的has_many。像这样的东西应该有希望的工作。的has_many:用户:通过=&GT; :如下,:选择=&GT; 用户。*,follows.is_admin为is_follow_admin
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'
然后在循环,你应该能够访问 user.is_follow_admin
Then in the loop you should have access to user.is_follow_admin
这篇关于需要得到轨数据连接表的has_many:通过的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!