开发者

Rails: has_many, but also has_one by a different name

开发者 https://www.devze.com 2022-12-18 22:06 出处:网络
Let\'s say a User has many Documents, and a single Document they\'re currently working on. How do I represent this in rails?

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 remov开发者_如何学Ces 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消