以下是我的协会:
class Agency < ActiveRecord::Base
has_many :agencies_hotline_services, dependent: :destroy
has_many :hotline_services, through: :agencies_hotline_services
end
#rich join table between agencies and hotline_services
class AgenciesHotlineService < ActiveRecord::Base
belongs_to :hotline_service
belongs_to :agency
end
class HotlineService < ActiveRecord::Base
belongs_to :hotline_service_category
has_many :agencies_hotline_services
has_many :agencies, through: :agencies_hotline_services
end
class HotlineServiceCategory < ActiveRecord::Base
has_many :hotline_services
end
当用户创建新的agency
时,我会使用nested_form_fields gem,以便用户可以为hotline_services
动态添加新的agency
:
点击添加服务时,此代理商提供按钮:
当用户从该选择框中选择hotline_service_category
时,会调用ajax请求,然后将hotline_service
选择更新为仅与所选hotline_services
相关联的hotline_service_category
:
在创建 new agency
时,这一切都非常有效。我遇到麻烦的地方是我想编辑现有的agency
:
agency
表单的nested_fields部分正确显示了每个代理商关联的hotline_services
的现有选定选项。但是,表单不会显示每个hotline_service_category
的关联hotline_service
选项。我想显示hotline_service_category
的现有选定选项。
注意:hotline_service_category
未保存在富连接表中。通过关联的hotline_service
来抓住它。
所以我的收藏集选择了hotline_service_category
,我想说:嘿,看看位于此一下方的collection_select中的所选hotline_service
选项,抓住关联的hotline_service_category
,并将其显示为hotline_service_category
的选定选项。
以下是_form.html.erb
的{{1}}相关代码:
agency
答案 0 :(得分:1)
hotline_service_category
未存储在数据库中(它不是嵌套表单&#34;知道&#34;的属性的一部分),这就是为什么它不会自动设置它。
HotlineService belongs_to :hotline_service_category
因此hotline_service
将在hotline_service_category_id
所以你可以做的是检查是否有hotline_service
,如果它存在,请取hotline_service_category_id
并将collection_select
选中的值设置为hotline_service_category_id
所以您需要做的就是添加selected
这样的值:
<%= collection_select(:hotline_service_category_id, .... {selected: ID} ) %>
您可以像这样获取嵌套对象:ff.object
属于agencies_hotline_services
类型。
然后您可以使用:ff.object.hotline_service.hotline_service_category_id
您应该使用try
来避免出现错误。这样:
ff.object.try(:hotline_service).try(:hotline_service_category_id)
但是您应首先检查记录是否不是新记录,因为如果记录不新,则不要设置所选值。你可以通过检查:
来做到这一点ff.object.new_record?
所以让我们结合一切,你会得到:
!ff.object.new_record? && ff.object.try(:hotline_service).try(:hotline_service_category_id) ? {} : {selected: ff.object.try(:hotline_service).try(:hotline_service_category_id) }
将其添加到您的collection_select
字段,并设置值。
更简洁的方法是使用其他变量来存储它,这样收集选择就不会那么长。
<% selected_value = ff.object.try(:hotline_service).try(:hotline_service_category_id) if !ff.object.new_record? %>
然后只需添加:
selected_value ? {} : {selected: selected_value }
***我不确定&#34;已选择:ID&#34;是设置所选值的方法,也许您需要类别的名称或集合中类别的位置,但我确定您可以自己找到它。
修改强>
我使用enum作为collection_select。 我可以使用它显示的字符串设置集合的选定值。 (在我的例子中:模型的名称) 所以你可以试试:
ff.object.try(:hotline_service).try(:hotline_service_category).try(:description)
或包含所显示类别文本的字段名称。