Rails: has_many, but also has_one with a different name

Let's say a Userhas many Documents and one Documentthat they are currently working on. How to present it in rails?

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

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_documentit deletes the document previously saved in current_user.document, from current_user.documents. It makes sense because of the relationship has_onethat it has Document, but that’s not what I want. How to fix it?

+5
source share
1 answer

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. . ( ) current_document, , .

+8

All Articles