問題: 我需要過濾一組單元的集合,其基礎是選擇一組組織。Rails 4:如何通過AJAX更新基於另一個collection_select的collection_select?
在選擇組織,則單位下拉菜單應只刷新,顯示單位屬於知情組織。
我檢查了這些問題:
Rails forms: updating collection_select options based on other collection_select value using AJAX
Rails forms: updating collection_select options based on other collection_select value using AJAX
Rails form_for collection_select ignoring remote ajax call that select_tag accepts
而且這些單證:
- 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
查看 應用程序/視圖/項目/ _form.html.erb
<%= 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
我怎樣才能使這項工作?
如果您仍希望組織爲用戶選擇能夠縮小選項範圍需要實現它作爲ajax調用。但是,這本身就是整個教程,如果你是新手入門,那麼以後可能會更好。 – max
感謝@max的提醒,我會用你的答案重構代碼:)關於ajax,我想這就是我的意圖,我會重新回答這個問題。我在rails上使用ajax做了一些基本的事情,比如livesearch過濾器,排序和分頁,還設置了視圖模板來響應模態,但是我對JS和Rails之間「對話」的瞭解非常有限,您知道任何我可以更多地瞭解它的地方?謝謝 –
我不使用'js.erb'或內置'remote:true'選項。恕我直言,它只是導致服務器端和客戶端邏輯和糟糕的API的總clusterfuck。它是鐵軌中最糟糕的部分之一。我只使用普通的舊jquery ajax處理程序和來自控制器的JSON響應。 – max