扶手:的has_many,也HAS_ONE一个不同的名称 [英] Rails: has_many, but also has_one by a different name

查看:87
本文介绍了扶手:的has_many,也HAS_ONE一个不同的名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说,一个用户有许多文件 s和一个文件他们目前正在努力。我该如何重新present这在轨?

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

我想说 current_user.current_document = Document.first (有或没有在CURRENT_文件前)和拥有它不改变 CURRENT_USER .documents 集合。

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.

这是我有:

class Document < ActiveRecord::Base
  belongs_to :user
end

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

问题是,当我说 current_user.document = some_document ,它会删除该文件previously存储在 current_user.document current_user.documents 。这是有道理的,由于 HAS_ONE 关系,即文件有,但不是我想要的。如何解决呢?

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?

推荐答案

您需要更改模型,以

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 ,然后保存,你可能会得到堆栈溢出或其他疯狂错误的用户。

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.

这篇关于扶手:的has_many,也HAS_ONE一个不同的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆