1

我有这样的关系:

组织:

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但没有用。

4

1 回答 1

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您的组织中。显然,这取决于您的应用程序的逻辑。

于 2012-08-13T02:11:46.487 回答