【发布时间】:2015-11-03 17:34:28
【问题描述】:
这是我的关联:
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,以便用户可以为agency 动态添加新的hotline_services:
当点击添加该机构提供的服务按钮时:
当用户从该选择框中选择hotline_service_category 时,将调用一个ajax 请求,然后将hotline_service 选择更新为仅与所选hotline_service_category 关联的hotline_services:
在创建 new agency 时,这一切都非常有用。我遇到麻烦的地方是当我想编辑现有的agency:
agency 表单的nested_fields 部分正确显示了每个代理机构关联的hotline_services 的现有选定选项。但是,表单不显示每个hotline_service 的关联hotline_service_category 选项选择。我确实想显示 hotline_service_category 的现有选定选项。
注意:hotline_service_category 未保存在富连接表中。通过关联的hotline_service 获取它。
因此,不知何故,我的集合选择为hotline_service_category,我想说:嘿,查看位于此选项下方 collection_select 中的选定hotline_service 选项,获取关联的hotline_service_category,并将其显示为hotline_service_category 的选定选项。
这是来自_form.html.erb 的agency 的相关代码:
<%= f.nested_fields_for :agencies_hotline_services do |ff| %>
<div class="row">
<div class="col-sm-4 form-group">
<%= label_tag "Service Category" %>
<%= collection_select(:hotline_service_category_id, nil, HotlineServiceCategory.all, :id, :description, {prompt: '-Select-'}, class: "form-control", id: "new_edit_hotline_service_category_selection") %>
</div>
<div class="col-sm-5 form-group">
<%= ff.label "Service Provided" %>
<%= ff.collection_select(:hotline_service_id, HotlineService.all, :id, :description, {}, class: "form-control hotline_service_selection") %>
</div>
<div class="col-sm-3">
<br>
<%= ff.remove_nested_fields_link "Remove", class: "btn btn-small btn-danger "%>
</div>
</div>
<% end %>
<%= f.add_nested_fields_link :agencies_hotline_services, "Add a Service this Agency Provides", class: "btn btn-primary" %>
【问题讨论】:
标签: ruby-on-rails ruby