I\'ve been trying to get some dynamic select functionality working, but despite many different tutorial i\'ve yet to get it to work. For ease of reading, i\'ve brought the c
Gotcha. Using UJS you can dynamically populate your select in 5 steps.
So,
Add class names:
<%= 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"} %>
Throw in some CoffeeScript (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()
Update your faults controller
def get_contacts
@company = Company.find params[:company_id]
@contacts = @company.contacts
end
Add a route to your new method
resources :faults do
collection do
get 'get_contacts', to: "faults#get_contacts"
end
end
Add the UJS file (app/views/faults/get_contacts.js.erb)
$('.contact_selection').empty();
$('.contact_selection').append( $(''));
<% @contacts.each do |contact| %>
$('.contact_selection').append($(''));
<% end %>