Rails 5: Nested forms and existing associated objects

╄→尐↘猪︶ㄣ 提交于 2019-12-24 16:41:03

问题


I'm relatively new to Rails so please forgive me if this turns out to be quite a naive question. :]

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.

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?

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.

Any help or advice will be greatly appreciated.


回答1:


you need to do it manually, it's not that much code.

Similar question

Basically, you'll need find_or_create_by in your controller (doc) and fields_for (doc) in your Collection and Video views.



来源:https://stackoverflow.com/questions/37595050/rails-5-nested-forms-and-existing-associated-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!