質問

I'm trying to model my MongoDB database with Mongoid, and trying to create relations for the following relationship:

  • User can own a Project
  • Project is owned by User
  • User can be a collaborator in a Project (but not an owner)
  • Project has many collaborators (Users)

So basically, a user can own projects and collaborate on a project. These are two different roles. An owner, a User, through the 1-N relationship, can perform tasks on a project. A collaborator, a User, through the N-N relationship, can perform a separate set of tasks on a project.

The solution I came up with is this:

# app/models/user.rb
class User
  include Mongoid::Document
  include Mongoid::Timestamps

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

  has_many :projects
end

# app/models/project.rb
class Project
  include Mongoid::Document
  include Mongoid::Timestamps

  field :title,     type: String
  field :summary,   type: String
  field :permalink, type: String
  field :collaborator_ids, type: Array, default: []

  belongs_to :user

  def collaborators
    arr = []

    self.collaborator_ids.each do |id|
      arr << User.find(id)
    end

    arr
  end
end

It's obviously not ideal: is there another way to do this? I'd much rather use Mongoid's has_and_belongs_to_many relationship instead of the ObjectIDs in an Array hack that I have.

役に立ちましたか?

解決

As requested, I'll move my comment into an answer:

I recommend creating an :owner_id field for each project and then creating a has_and_belongs_to_many relationship between the User and Project models. Then create some simple functions to determine who the owner of a project is, who the collaborators are etc

# app/models/project.rb
class Project
  include Mongoid::Document
  include Mongoid::Timestamps

  field :title,     type: String
  field :summary,   type: String
  field :permalink, type: String
  field :owner_id,  type: String

  has_and_belongs_to_many :users

  def is_owner?(owner_object)
    return self.owner_id == owner_object.id
  end

  # Add more functions here based on your needs

end
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top