Has_many,通过关联 [英] Has_many, through association

查看:45
本文介绍了Has_many,通过关联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

警告:Total Rails Newb (TRN).这应该是一个非常基本的问题,所以我希望有人能抽出几分钟来帮助阐明.

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.

我将如何构建它?

最初我试过这个:

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

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

推荐答案

它会很有用: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

这篇关于Has_many,通过关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆