需要来自rails join table的数据,has_many:through
我有3个表 – 用户,东西和以下。 用户可以通过以下表格进行操作,将user_id
与things_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”,我希望能够访问该关系。 所以在循环中我可以做类似的事情:
有没有办法将关系包含在原始用户对象中? 我试过:select => "follows.relation"
,但它似乎没有加入属性。
为此,您需要在has_many中使用一些SQL。 这样的事情应该会有所作为。 has_many :users, :through => :follows, :select => 'users.*, follows.is_admin as is_follow_admin'
然后在循环中,您应该可以访问user.is_follow_admin
对于使用rails 4的人,不推荐使用:order,:select等。 现在您需要指定如下:
has_many :users, -> { select 'users.*, follows.is_admin as is_follow_admin' }, :through => :follows
你可以做类似的事情:
<% things.follows.each do |follow| %> <%= follow.relation %> <%= follow.user %> <% end %>