用户/组织与mongoid的关系

时间:2012-08-12 20:28:11

标签: ruby ruby-on-rails-3 mongoid

我有这样的关系:

组织:

class Organization
  include Mongoid::Document
  include Mongoid::Timestamps

  field :name, type: String
  field :email, type: String

  has_and_belongs_to_many :users
end

用户:

class User
  include Mongoid::Document
  include Mongoid::Timestamps
  include ActiveModel::SecurePassword

  has_secure_password

  #Fields
  field :nick, type: String
  field :name, type: String
  field :email, type: String
  field :password_digest, type: String #for bcrypt-ruby

  #Validations
  ## Presence
  validates :nick, presence: true
  validates :email, presence: true
  validates :password, presence: true, :on => :create

  #Uniqueness
  validates :nick, uniqueness: true
  validates :email, uniqueness: true

  #Relations
  has_many :documents, dependent: :delete
  has_many :storages, dependent: :delete

  has_and_belongs_to_many :organizations
end

我可以保存组织和用户。这种关系工作正常,但现在我想将一个所有者添加到组织,这也是一个用户。 我试过has_one :user, as: :owner但没有用。

1 个答案:

答案 0 :(得分:2)

尝试将此添加到您的organization.rb:

has_one :owner, class_name: "User", inverse_of :owns

并将其添加到您的user.rb:

belongs_to :owns, class_name: "Organization", inverse_of :owner

或者,如果您愿意,可以撤消逻辑并将has_one放入您的用户类和组织中的belongs_to。这显然取决于你的应用程序的逻辑。