我一直在尝试使一些动态选择功能起作用,但是尽管有许多不同的教程,我仍未使其起作用。为了便于阅读,我将代码示例简化为基础。任何建议将不胜感激。
在“故障”页面上,我需要分配公司并联系故障,但是我只希望能够看到与所选公司相关的联系人
Fault - belongs_to :company, :user, :contact
User - has_many :faults
Contacts - has_and_belongs_to_many :companies
Company - has_and_belongs_to_many :contacts, has_many :faults
/faults/_form.html.erb
<%= f.label :company, "Company:" %>
<%= collection_select(:fault,:company_id,@companies,:id,:full_name, :prompt => "Please select a company") %></br>
<%= f.label :contact, "Contact:" %>
<%= f.collection_select :contact_id, @contacts, :id, :name, :prompt => "Select a Contact" %>
<%= link_to "Add New Contact", {:controller => "companies", :action => "index"}, :confirm => "To add a contact for a company you need to do this from the companies page." %></br>
最佳答案
知道了使用UJS,您可以通过5个步骤动态填充选择内容。
所以,
<%= f.label :company, "Company:" %>
<%= collection_select(:fault,:company_id,@companies,:id,:name, {:prompt => "Please select a company"}, {:class => "company_selection"}) %>
<%= f.label :contact, "Contact:" %>
<%= f.collection_select :contact_id, @contacts, :id, :name, {:prompt => "Select a Contact"}, {:class=>"contact_selection"} %>
app/assets/javascripts/faults.js.coffee
)$(document).ready ->
$(".company_selection").on "change", ->
$.ajax
url: "/faults/get_contacts"
type: "GET"
dataType: "script"
data:
company_id: $('.company_selection option:selected').val()
def get_contacts
@company = Company.find params[:company_id]
@contacts = @company.contacts
end
resources :faults do
collection do
get 'get_contacts', to: "faults#get_contacts"
end
end
app/views/faults/get_contacts.js.erb
)$('.contact_selection').empty();
$('.contact_selection').append( $('<option>Select the Contact</option>'));
<% @contacts.each do |contact| %>
$('.contact_selection').append($('<option value="<%= contact.id %>"><%= contact.name %></option>'));
<% end %>
关于ruby-on-rails - Rails-动态选择-集合选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19909394/