【问题标题】:Need data from rails join table, has_many :through需要来自 rails 连接表的数据,has_many :through
【发布时间】:2012-02-11 01:56:28
【问题描述】:

我有 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 =&gt; "follows.relation",但是好像没有加入属性。

【问题讨论】:

  • 将关系命名为“关系”是一个非常糟糕的主意...这可能会破坏一些 ruby​​ 内部结构,您会得到意想不到的行为!
  • 好的,谢谢。假设该列名为“is_admin”并且具有布尔类型..

标签: ruby-on-rails associations has-many-through has-many


【解决方案1】:

对于使用 rails 4 的用户,:order、:select 等的使用已被弃用。现在你需要指定如下:

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

【讨论】:

    【解决方案2】:

    你也许可以这样做:

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

    【讨论】:

      【解决方案3】:

      为此,您需要在 has_many 中使用一些 SQL。这样的事情应该有望奏效。 has_many :users, :through =&gt; :follows, :select =&gt; 'users.*, follows.is_admin as is_follow_admin'

      然后在循环中你应该可以访问 user.is_follow_admin

      【讨论】:

      • 绝对有效,并且基本上是我之前尝试过的。我的挂断是在命令行上执行此操作时的 SQL 转储不会在任何地方显示 is_admin 属性。它只显示以下对象。谢谢!
      • Rails4 已弃用:选择我认为。现在是如何实现的?
      • 我使用的是 rails 4,这种格式可以工作 has_many :users, -&gt; { select('users.*, members.role as member_role') }, through: :members
      • @Matt Gaidica,您应该将此添加到您的用户模型中(以使属性可访问)-def is_follow_admin attributes['is_follow_admin'] end
      猜你喜欢
      • 1970-01-01
      • 2011-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-04
      相关资源
      最近更新 更多