Advertisement
fauzieuy

Select tag Association With Javascript - Ruby On Rails

Feb 16th, 2013
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rails 1.13 KB | None | 0 0
  1. // Javascript
  2.  
  3. function update_states_div(country_id) {  
  4.   jQuery.ajax({
  5.     url: "/update_states",
  6.     type: "GET",
  7.     data: {"country_id" : country_id},
  8.     dataType: "html"
  9.     success: function(data) {
  10.       jQuery("#statesDiv").html(data);
  11.     }
  12.   });
  13. }
  14.  
  15.  
  16. // Controller
  17.  
  18. def new
  19.   @User = User.new
  20.   @countries = Country.all
  21.   @states = State.al
  22. end
  23.  
  24. def edit
  25.   @User = User.find(params[:id])
  26.   @countries = Country.all
  27.   @states = State.all
  28. end
  29.  
  30. def update_states
  31.   @states = State.where(country_id => params[:country_id])
  32.   render :partial => "states", :object => @states
  33. end
  34.  
  35.  
  36. // View
  37.  
  38. <%= select_tag "country_id", options_from_collection_for_select(@countries, "id", "name"), :prompt => "Select Your Country", :onchange => "update_states_div(this.value)" %>
  39. <div id="statesDiv">
  40.   <%= render :partial => 'states', :object => @states %>
  41. </div>
  42.  
  43.  
  44. // Partial: _state.html.erb
  45.  
  46. <%= select_tag "state_id", options_from_collection_for_select(states, "id", "name"), :prompt => "Select State" %>
  47.  
  48. // Also add a route for /update_states in your routes.rb
  49.  
  50. match "/update_states" => "users#update_states"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement