【发布时间】: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