Skip to content

Instantly share code, notes, and snippets.

@bmarcot
Last active September 19, 2017 09:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save bmarcot/9169913 to your computer and use it in GitHub Desktop.
Save bmarcot/9169913 to your computer and use it in GitHub Desktop.
Dynamic Select Boxes for Rails 4 (full) @ https://github.com/bmarcot/dynamic-select-boxes
# app/assets/javascripts/welcome.js.coffee
$ ->
$(document).on 'change', '#countries_select', (evt) ->
$.ajax 'update_cities',
type: 'GET'
dataType: 'script'
data: {
country_id: $("#countries_select option:selected").val()
}
error: (jqXHR, textStatus, errorThrown) ->
console.log("AJAX Error: #{textStatus}")
success: (data, textStatus, jqXHR) ->
console.log("Dynamic country select OK!")
# app/controllers/welcome/controller.rb
class WelcomeController < ApplicationController
def index
@countries = Country.all
@cities = City.where("country_id = ?", Country.first.id)
end
def show
@city = City.find_by("id = ?", params[:trip][:city_id])
end
def update_cities
@cities = City.where("country_id = ?", params[:country_id])
respond_to do |format|
format.js
end
end
end
# app/models/city.rb
class City < ActiveRecord::Base
belongs_to :country
end
<!-- app/views/cities/_city.html.erb -->
<option value="<%= city.id %>"><%= city.name.titleize %></option>
<!-- app/views/welcome/index.html.erb -->
<%= form_for :trip, url: {action: "show"}, html: {method: "get"} do |f| %>
<%= f.select :country_id, options_for_select(@countries.collect { |country|
[country.name.titleize, country.id] }, 1), {}, { id: 'countries_select' } %>
<%= f.select :city_id, options_for_select(@cities.collect { |city|
[city.name.titleize, city.id] }, 0), {}, { id: 'cities_select' } %>
<%= f.submit "Go!" %>
<% end %>
<!-- app/views/welcome/show.html.erb -->
<p><%= @city.name.titleize %></p>
<p><%= link_to 'Go Back', welcome_index_path %></p>
# app/views/welcome/update_cities.js.coffee
$("#cities_select").empty().append("<%= escape_javascript(render(:partial => @cities)) %>")
# config/routes.rb
get 'welcome/update_cities', as: 'update_cities'
get 'welcome/show'
# db/seeds.rb
Country.create(name: "france")
Country.create(name: "italy")
City.create(name: "paris", country_id: Country.find_by(name: "france").id)
City.create(name: "nice", country_id: Country.find_by(name: "france").id)
City.create(name: "roma", country_id: Country.find_by(name: "italy").id)
City.create(name: "venezia", country_id: Country.find_by(name: "italy").id)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment