如何指定has_many通过vs has_many
问题描述:
所以我想弄清楚如何基于has_many和has_many:通过关联调用一个对象的所有实例。我有用户,组和成员。成员模型是组和用户的配对。该组还在该模型中具有user_id。所以这会更有意义之后,你看到的代码:如何指定has_many通过vs has_many
用户模型
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 %>
我想弄清楚如何在索引视图中调用不同类型的关联用户和组。
我想要列出所有列为admin(group.user_id)的组,然后我想获得我是其成员的所有组的单独列表(通过成员模型)。
我知道我可以用find或where调用来查询它。但是,我希望有一个像current_user.groups之类的简单方法。不管怎样,谢谢!
答
我会考虑调用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路由回组模型?我从来没有见过,这很酷 – 2014-09-25 19:18:24
好吧,我实现了这个改变,但我得到了一个奇怪的错误“无法找到关联:模型用户成员”,但在我的用户模型中,我有:“has_many:groups,: through =>:members“此外,此错误突出显示了这一行:”current_user.groups.order ....“ – 2014-09-25 19:36:46
对不起,由1表示:NI表示用户和其拥有的组之间的”一对多“关系。用户和组之间通过成员表的N:N关系。 – GSP 2014-09-25 19:36:50