Rails 4:如何通过AJAX更新基于另一个collection_select的collection_select?
问题:我需要根据组织集合的选择过滤单位集合。
选择组织后 , 单位下拉菜单应刷新以仅显示属于知情组织的单位 。
我检查过这些问题:
-
Rails表单:使用AJAX基于其他collection_select值更新collection_select选项
-
UJS,AJAX,Rails 4,form_for collection_select将值传递给方法并将值返回到表单
-
带有collection_select的rails中的ajax
-
如何添加onchange事件以在rails中选择标记
-
Rails表单:使用AJAX基于其他collection_select值更新collection_select选项
-
Rails form_for collection_select忽略select_tag接受的远程ajax调用
-
远程选择,控制器需要更多表格数据
这些文件:
- http://guides.rubyonrails.org/form_helpers.html
- http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html
- http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-options_from_collection_for_select
到目前为止这是我的代码:
楷模
class Organization < ActiveRecord::Base has_many :units has_many :projects, through: :units end class Unit < ActiveRecord::Base belongs_to :organization has_many :projects end class Project < ActiveRecord::Base belongs_to :organizaton has_one :organization, through: :unit end
查看 app / views / projects / _form.html.erb
控制器 项目控制器
def new @project = Project.new end def project_params params.require(:project).permit(:name, :description, :organization_id, :unit_id) end
我怎样才能做到这一点?
我做到了,解决方案非常简单,但缺乏关于这个简单问题的更新材料使它成为一个比它应有的更大的苦差事:
配置/ routes.rb中
get 'filter_units_by_organization' => 'projects#filter_units_by_organization'
控制器/ projects_controller.rb
def filter_units_by_organization @filtered_units = Unit.where(organization_id: params[:selected_organization]) end
意见/项目/ filter_units_by_organization.js.erb
$('select#project_unit_id').html('<%= j options_from_collection_for_select(@filtered_units, :id, :name) %>');
资产/ Java脚本/ application.js中
$(function() { $("select#project_organization_id").on("change", function() { $.ajax({ url: "/filter_units_by_organization", type: "GET", data: { selected_organization: $("select#project_organization_id").val() } }); }); });
意见/项目/ _form.html.erb
<%= f.label :name %>
<%= f.text_field :name %> <%= f.label :description %>
<%= f.text_area :description %> <%= f.label :organization_id %>
<%= f.collection_select :organization_id, Organization.all, :id, :name, { prompt: 'Please select' } %> <%= f.label :unit_id %>
<%= f.collection_select :unit_id, Unit.all.where(organization_id: :organization_id), :id, :name %> <%= f.submit %>
您应该将关系设置为通过单元模型,而不是在projects
表上放置重复的organization_id
。
class Organization < ActiveRecord::Base has_many :units has_many :projects, through: :units end class Unit < ActiveRecord::Base belongs_to :organization has_many :projects end class Project < ActiveRecord::Base belongs_to :unit has_one :organizaton, through: :unit end
这避免了您必须确保单元和项目具有相同的organizaton_id
的尴尬问题。
这也意味着您在创建项目时不再需要输入来选择组织 - 只需要单位。