views:

60

answers:

1

Let's say a User has many Documents, and a single Document they're currently working on. How do I represent this in rails?

I want to say current_user.current_document = Document.first (with or without current_ in front of document) and have it not change the current_user.documents collection.

This is what I have:

class Document < ActiveRecord::Base
  belongs_to :user
end

class User < ActiveRecord::Base
  has_many :documents
  has_one :document
end

the problem is that when I say current_user.document = some_document, it removes the document previously stored in current_user.document from current_user.documents. This makes sense due to the has_one relationship that Document has, but isn't what I want. How do I fix it?

+3  A: 

You need to change your Models to

class Document < ActiveRecord::Base
  belongs_to :user
end

class User < ActiveRecord::Base
  has_many :documents

  # you could also use :document, but I would recommend this:
  belongs_to :current_document, :class_name => "Document"
end

P.S. But beware of cyclic saves. If you create a new User (and don't save it yet) and set current_document and then save the User you might get stack overflows or other crazy errors.

Marcel J.
Thanks! And just to be clear for others, the column name in this case will be `current_document_id` in the `users` table.
Peter