简体   繁体   English

如何在Rails中将表单选择输入用于多态的Emirates_to关联?

[英]How do you use a form select input for a polymorphic belongs_to association in Rails?

I've got an Article model that has a polymorphic belongs_to association (resource). 我有一个Article模型,该模型具有多态的belongs_to关联(资源)。 I've been trying to let it set the association from the article form via two select boxes, one with the type and the other with id of the association as shown below. 我一直试图让它通过两个选择框从文章表单中设置关联,一个具有类型,另一个具有关联ID,如下所示。

= form_for @article do
  = f.select :resource_type, ...
  = f.grouped_collection_select :resource_id, ...

My problem is that it doesn't select the correct model in the grouped_collection_select if the association id exists in two of the associated models. 我的问题是,如果关联ID存在于两个关联模型中,则它不会在grouped_collection_select中选择正确的模型。

There must be a better way to do this but I just can't seem to see it right now. 一定有更好的方法可以做到这一点,但我似乎暂时看不到它。

One way to handle it is to allow toggling between resources with a javascript function. 一种解决方法是允许使用javascript函数在资源之间进行切换。 You have a link that is bound to a javascript function that swaps out one resource select box for another. 您有一个绑定到JavaScript函数的链接,该JavaScript函数将一个资源选择框换为另一个资源选择框。

There's a railscast that describes how to do this. 有一个介绍如何做到这一点的栏杆。 Ignore the nested form and add/remove business and focus on the essentials (javascript-bound link, helper methods, etc): http://railscasts.com/episodes/197-nested-model-form-part-2 . 忽略嵌套表单并添加/删除业务,而将重点放在要点(javascript绑定链接,帮助器方法等)上: http : //railscasts.com/episodes/197-nested-model-form-part-2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM