作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
问题:
我需要根据组织集合的选择来过滤单位集合。
选择单位后,单位下拉菜单应刷新以仅显示属于已知单位的单位。
我检查了以下问题:
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
<%= form_for(@project) do |f| %>
<div class="field">
<%= f.label :name %><br>
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :description %><br>
<%= f.text_area :description %>
</div>
<div class="field">
<%= f.label :organization_id %><br>
<%= f.collection_select :organization_id, Organization.all, :id, :name %>
</div>
<div class="field">
<%= f.label :unit_id %><br>
<%= f.collection_select :unit_id, Unit.all.where(organization_id: :organization_id), :id, :name %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
def new
@project = Project.new
end
def project_params
params.require(:project).permit(:name, :description, :organization_id, :unit_id)
end
最佳答案
我做到了,解决方案非常简单,但是由于缺少有关此简单问题的更新资料,因此使它比应做的事情繁琐得多:
config/routes.rb
get 'filter_units_by_organization' => 'projects#filter_units_by_organization'
def filter_units_by_organization
@filtered_units = Unit.where(organization_id: params[:selected_organization])
end
$('select#project_unit_id').html('<%= j options_from_collection_for_select(@filtered_units, :id, :name) %>');
$(function() {
$("select#project_organization_id").on("change", function() {
$.ajax({
url: "/filter_units_by_organization",
type: "GET",
data: { selected_organization: $("select#project_organization_id").val() }
});
});
});
<div class="field">
<%= f.label :name %><br>
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :description %><br>
<%= f.text_area :description %>
</div>
<div class="field">
<%= f.label :organization_id %><br>
<%= f.collection_select :organization_id, Organization.all, :id, :name, { prompt: 'Please select' } %>
</div>
<div class="field">
<%= f.label :unit_id %><br>
<%= f.collection_select :unit_id, Unit.all.where(organization_id: :organization_id), :id, :name %>
</div>
<div class="actions">
<%= f.submit %>
</div>
关于ruby-on-rails - Rails 4 : How to update a collection_select based on another collection_select through AJAX?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37230426/
我是一名优秀的程序员,十分优秀!