Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: has_many, but also has_one by a different name

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?

like image 463
Peter Avatar asked Feb 04 '10 10:02

Peter


1 Answers

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.

like image 105
Marcel Jackwerth Avatar answered Oct 14 '22 23:10

Marcel Jackwerth