警告:Total Rails Newb(TRN).这应该是一个非常基本的问题,所以我希望有人可以节省几分钟来帮助解决问题.
假设我有以下模型:用户,组和成员
用户可以拥有多个群组(比方说朋友,家人等)
一个组可以有许多成员,即其他用户.
我该如何构建这个?
最初我试过这个:
class User < ActiveRecord::Base has_many :groups has_many :groups,:through => :members end class Groups < ActiveRecord::Base has_many :users,:through => :members belongs_to :user end class Member < ActiveRecord::Base belongs_to :group belongs_to :user end
has_many :groups,:through => :members
至
has_many :memberships,:through => :members,:source => :groups
我尝试做的时候仍然会收到关于缺少关联的错误
group = Group.new group.user.new
解决方法
这将是有用的:
http://railscasts.com/episodes/47-two-many-to-many
class User < ActiveRecord::Base has_many :members has_many :groups,:through => :members has_many :groups_as_owner,:class_name => "Group" end class Groups < ActiveRecord::Base has_many :members has_many :users,:through => :members belongs_to :owner,:class_name => "User",:foreign_key => :user_id end class Member < ActiveRecord::Base belongs_to :group belongs_to :user end