Let's say a User
has many Document
s, 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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With