ruby-on-rails-3 – Has_many,通过协会

前端之家收集整理的这篇文章主要介绍了ruby-on-rails-3 – Has_many,通过协会前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
警告: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

猜你在找的Ruby相关文章