Topic: 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,

Re: Relationships question (?)

You shouldn't have any problems with document relating to user in two different ways. The only thing you need to watch out for is if you are doing a complex quiery which joins the users table twice because of the association. But other then that, it should be fine.

The convention is to call the column user_id and will save you a few keystrokes, but since owner_id is more descriptive I recommend sticking with that. If the name of the model can't be determined from the name of the foreign key you'll just need to specify it in the association, like this:

class Document < ActiveRecord::Base
  belongs_to :owner, :foreign_key => 'owner_id', :class_name => 'User'
  has_and_belongs_to_many :users

The User side of the association is also a little tricky because it has_many documents in two different ways. You'll need to give one of them a different name, like this:

class User < ActiveRecord::Base
  has_and_belongs_to_many :documents
  has_many :documents_as_owner, :foreign_key => 'owner_id', :class_name => 'Document'

Railscasts - Free Ruby on Rails Screencasts