【问题标题】:how to specify has_many through vs has_many如何通过 vs has_many 指定 has_many
【发布时间】:2014-09-25 07:08:16
【问题描述】:

所以我试图弄清楚如何在调用基于 has_many 和 has_many 的对象的所有实例之间指定:通过关联。我有用户、组和成员。成员模型是组和用户的配对。这些组在该模型中也有一个 user_id。所以看到代码后这会更有意义:

用户模型

class User < ActiveRecord::Base
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  has_many :groups
  has_many :groups, :through => :members
end

群模型

class Group < ActiveRecord::Base
    has_many :users, :through => :members
    belongs_to :user
end

成员模型

class Member < ActiveRecord::Base
  belongs_to :groups
  belongs_to :users
end

索引视图

<!--these are the groups I own (the group.user_id is my id) NEEDS EDITING-->
  <% @groups.each do |group| %>
      <%= link_to group.title, group_path(group) %>
      <%= truncate group.desc %>
  <% end %>

<!--I'm a member of these groups (connected through the member model) NEEDS EDITING'-->
  <% current_user.groups.order(:created_at).each do |group| %>
      <%= link_to group.title, group_path(group) %>
      <%= truncate group.desc %>
  <% end %>

我试图弄清楚如何在索引视图中调用不同类型的关联用户和组。

我想获取将我列为管理员 (group.user_id) 的所有组的列表,然后我想获取我所属的所有组的单独列表(通过成员模型) .

我知道我可以通过 find 或 where 调用来查询它。但是,我希望有像 current_user.groups 之类的简单方法。总之感谢!

【问题讨论】:

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


    【解决方案1】:

    我会考虑将 1:N 关系称为另一个名称。所以你最终会得到类似的东西

    class User < ActiveRecord::Base
      devise :database_authenticatable, :registerable,
             :recoverable, :rememberable, :trackable, :validatable
    
      has_many :owned_groups, class_name: 'Group'
      has_many :groups, :through => :members
    end
    

    所以索引视图看起来像:

    <% current_user.owned_groups.each do |group| %>
        <%= link_to group.title, group_path(group) %>
        <%= truncate group.desc %>
    <% end %>
    
    
    <% current_user.groups.order(:created_at).each do |group| %>
        <%= link_to group.title, group_path(group) %>
        <%= truncate group.desc %>
    <% end %>
    

    【讨论】:

    • 好的,我想我明白了,但我对 1:N 感到困惑。这到底是什么意思?另外,owned_groups 会是一个单独的模型吗?还是“class_name:'Group'”是否将owned_groups 路由回groups 模型?我以前从未见过,这很酷
    • 好的,我实现了这个更改,但我收到一个奇怪的错误“找不到关联:模型用户中的成员”,但在我的用户模型中,我有:“has_many :groups, :through => :members" ALSO,此错误突出显示以下行:"current_user.groups.order...."
    • 抱歉,1:N 我的意思是用户和她拥有的组之间的“一对多”关系。 N:N 关系将通过成员表在用户和组之间建立。
    • 哦,当然,谢谢,我现在在同一行代码上得到一个不同的错误:未初始化的常量 User::Groups。我认为这是因为名称与 Class_name“组”相同,所以有没有办法通过成员关联行将 class_name 'member' 添加到有很多:groups 中。我要试试这个
    • omg,在尝试了 100 种不同的事情之后,我想我最终回到了这个解决方案来修复未初始化的常量错误,并且我将成员类修复为单数属于。我想就是这样,以防有人遇到这个问题。感谢普惠制!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-18
    • 1970-01-01
    相关资源
    最近更新 更多