0

我有以下型号

Class User
  has_many :memberships

Class Membership
  belongs_to :user

成员资格表有两列,user_idorganization_id。但是,organization_id它也是一个用户 ID。

我怎样才能指定一个关联,以便:

@user.organizations返回此用户所属的组织(其他用户)的列表。

4

2 回答 2

2

我认为这样做的正确方法是创建三个模型,如下所示:

#user.rb
class User < ActiveRecord::Base
  has_many :memberships
  has_one :organization
end

#organization.rb
class Organization < ActiveRecord::Base
  attr_accessible :user_id
  belongs_to :user
  has_many :memberships
end

#membership.rb
class Membership  < ActiveRecord::Base
  attr_accessible :user_id, :organization_id
  belongs_to :user
  belongs_to :organization
end
于 2013-02-23T15:56:32.843 回答
0

弄清楚了:

class Membership < ActiveRecord::Base
  belongs_to :user
  belongs_to :organization, class_name: "User"
end

class User < ActiveRecord::Base
  has_many :memberships
  has_many :organizations, through: :memberships
end
于 2013-02-23T20:07:29.107 回答