Relationships question (?)

Hello there,

Im currently taking a Senior Design Course at my college. We are
developing an online document editor prototype with Rails.

I am not well-versed in Rails. As a matter of fact, we chose it for the
project in order to learn it.

The problem we have is the following:

We have a User model (id, username, password, email) and we have a
Document model (id, name, content, owner_id). A document can have many
users, because we are implementing a collaboration feature, but only one
owner. The owner will have administrative rights over the document (add
collaborators, delete, etc). Users will only be able to edit the
document.

The thing is, we need a documents_users table to handle the many-to-many
relationship. We do not know how to handle the owner, though, because in
essence the owner is also a user.

Do we need to implement an Owner model? Or can Rails handle two
different types of relationships between a couple of models?

In any case, should we still call the field for the owner in the
document table ‘owner_id’?

Thanks in advance,
az

azazel wrote:

We have a User model (id, username, password, email) and we have a
Document model (id, name, content, owner_id). A document can have many
users, because we are implementing a collaboration feature, but only one
owner. The owner will have administrative rights over the document (add
collaborators, delete, etc). Users will only be able to edit the
document.

The thing is, we need a documents_users table to handle the many-to-many
relationship. We do not know how to handle the owner, though, because in
essence the owner is also a user.

Do we need to implement an Owner model? Or can Rails handle two
different types of relationships between a couple of models?

In any case, should we still call the field for the owner in the
document table ‘owner_id’?

Thanks in advance,
az

You should not need an owner model, since an owner is just a user. Give
your Document table a field called owner_id and then use an association
like:

has_and_belongs_to_many :users
belongs_to :owner, :class_name => ‘User’, :foreign_key => :owner_id

Now you can do:

@document.owner #=> User object
@document.users #=> Array of User objects

if current_user == @document.owner
@document.users << User.find(123)
end

You can even encapsulate this into a model method to improve
readability:

class Document < ActiveRecord::Base
def owned_by?(user)
owner_id == user.id
end
end

doc = Document.find(1)
doc.owned_by? User.find(2) #=> false
doc.owned_by? User.find(3) #=> true

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs