Rails 5:嵌套表单和现有关联对象 [英] Rails 5: Nested forms and existing associated objects
问题描述
我对Rails比较陌生,因此如果发现这是一个非常幼稚的问题,请原谅我。 :]
I'm relatively new to Rails so please forgive me if this turns out to be quite a naive question. :]
我有两个可以标记的模型:收藏
和视频
。我通过带有多态关联的 Tag
模型和<$ c $ has_many:through 关联到标记
。所有这些都能完美地工作。
I have two models that can be tagged: Collection
and Video
. I support this via a Tag
model with a polymorphic association, and a has_many :through
association to Tagging
. All this works perfectly.
我很难弄清楚的是如何设置视图以适应这种情况。我知道,如果我仅创建或更新与单个模型唯一关联的标签,则可以使用简单的表单并将 accepts_nested_attributes_for
添加到我的模型中,但是问题是我我必须首先检查标记是否存在,并仅在不存在标记时创建它,否则,只需将现有标记与 new 视频或收藏集相关联即可。显然,我可以在控制器中手动执行此操作,但是由于Rails提供了一种自动创建和更新关联对象的机制,我想知道它是否提供了与关联现有对象类似的功能?
What I'm having a hard time figuring out is how to set up the views to accommodate this. I know that if I were only creating or updating tags that are uniquely associated with a single model then I could use a simple form and add accepts_nested_attributes_for
to my model, but the problem I'm having is that I want to first check for the existence of a tag, and only create it if it doesn't exist, otherwise just associate the existing tag with the new video or collection. Obviously I could do this manually in the controller, but since Rails provides a mechanism for creating and updating associated objects automatically, I wondered if it provided anything similar for associating existing objects?
此外,我不确定是否应该嵌套 tags
资源并在 TagsController
中集中处理,还是是否应该从拥有对象的控制器管理标签,例如 VideosController
。
Also, I'm not sure whether I should nest the tags
resource and handle this centrally in a TagsController
, or whether I should manage the tags from the owning object's controller, for instance VideosController
.
任何帮助或建议都会
推荐答案
您需要手动执行此操作,这不是很多代码。
you need to do it manually, it's not that much code.
基本上,您需要在控制器中使用 find_or_create_by
(文档)和 fields_for
(文档)在您的收藏夹和视频视图中。
Basically, you'll need find_or_create_by
in your controller (doc) and fields_for
(doc) in your Collection and Video views.
这篇关于Rails 5:嵌套表单和现有关联对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!