Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
891 views
in Technique[技术] by (71.8m points)

ruby on rails 3 - Has_many, through association

Warning:Total Rails Newb (TRN). This should be a pretty basic question so I'm hoping someone can spare a couple mins to help shed some light.

Let's say I have the following models: User, Group, and Member A user can have many groups (let's say friends, family, etc) A group can have many members, namely other users.

How would I structure this?

Initially I tried this:

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

However this gave me an error in User so I changed

has_many :groups, :through => :members

to

has_many :memberships, :through => :members, :source => :groups

Still getting an error about missing association when I try to do

group = Group.new
group.user.new
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It will be useful: 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...