需要来自 Rails 连接表的数据 has_many :through

发布于 2024-12-27 04:50:08 字数 610 浏览 0 评论 0原文

我有 3 个表 - 用户、事物和关注者。用户可以通过下表跟踪事物,将 user_idthings_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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

猫九 2025-01-03 04:50:08

为此,您需要在 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

我很坚强 2025-01-03 04:50:08

对于使用 Rails 4 的人来说,:order、:select 等的用法已被弃用。现在您需要指定如下:

has_many :users, -> { select 'users.*, follows.is_admin as is_follow_admin' }, :through => :follows

For people using rails 4, the usage of :order, :select, etc has been deprecated. Now you need to specify as follows:

has_many :users, -> { select 'users.*, follows.is_admin as is_follow_admin' }, :through => :follows
天邊彩虹 2025-01-03 04:50:08

您也许可以执行以下操作:

<% things.follows.each do |follow| %>
  <%= follow.relation %>
  <%= follow.user %>
<% end %>

You might be able to do something like:

<% things.follows.each do |follow| %>
  <%= follow.relation %>
  <%= follow.user %>
<% end %>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文