需要来自 rails 连接表的数据,has_many :through [英] Need data from rails join table, has_many :through

查看:30
本文介绍了需要来自 rails 连接表的数据,has_many :through的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 3 个表 - 用户、事物和关注.用户可以通过下表跟踪事物,将 user_idthings_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 %>

有没有办法将关系包含到原始用户对象中?我试过 :select =>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.

推荐答案

为此,您需要在 has_many 中使用一些 SQL.像这样的事情应该有希望工作.has_many :users, :through =>:follows, :select =>'users.*, follow.is_admin as 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

这篇关于需要来自 rails 连接表的数据,has_many :through的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆