需要来自 Rails 连接表的数据 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 。我的问题是,如果在下表中,我有一个名为“关系”的列,那么我可以将关注者设置为“管理员”,我想有权访问该关系。因此,在循环中我可以执行以下操作:
<% things.users.each do |user| %>
<%= user.relation %>
<% end %>
有没有办法将关系包含到原始用户对象中?我已经尝试过 :select => “follows.relation”
,但似乎没有加入该属性。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
为此,您需要在 has_many 中使用一些 SQL。像这样的东西应该会起作用。
has_many :users, :through =>; :跟随,:选择=> 'users.*, follow.is_admin as is_follow_admin'
然后在循环中您应该有权访问
user.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'
Then in the loop you should have access to
user.is_follow_admin
对于使用 Rails 4 的人来说,:order、:select 等的用法已被弃用。现在您需要指定如下:
For people using rails 4, the usage of :order, :select, etc has been deprecated. Now you need to specify as follows:
您也许可以执行以下操作:
You might be able to do something like: