Rails:具有相同模型的has_many和belongs_to

时间:2014-11-13 09:34:34

标签: ruby-on-rails mongoid

我有一个名为Team的资源,它属于一个用户(在client_id中),并且在Rails 3应用程序中应该有很多用户(在users中)。

如何指定

belongs_to :user

has_many :users

在一个型号中?

2 个答案:

答案 0 :(得分:1)

您是否尝试过has_and_belongs_to_many

http://apidock.com/rails/ActiveRecord/Associations/ClassMethods/has_and_belongs_to_many

http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#module-ActiveRecord::Associations::ClassMethods-label-Many-to-many

编辑:

它可能会像这样工作:

belongs_to :user # User is the owner
has_many :members, class_name: "User", foreign_key: "user_id"

答案 1 :(得分:1)

 # in models/team.rb
class Team
  belongs_to :client, class_name: 'User' # @team.client
  has_many :users # @team.users
end