Skip to content

Instantly share code, notes, and snippets.

@tessi
Last active December 16, 2015 22:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tessi/5505930 to your computer and use it in GitHub Desktop.
Save tessi/5505930 to your computer and use it in GitHub Desktop.
require 'ostruct'
include ActionView::Helpers::FormOptionsHelper
# fake ActiveRecord models
class Continent < OpenStruct
#attr_accessor :id, :name, :countries
def initialize(*args)
super
self.countries = []
end
end
class Country < OpenStruct
#attr_accessor :id, :name, :continent_id, :continent
def initialize(*args)
super
self.cities = []
end
end
class City < OpenStruct
#attr_accessor :id, :name, :country_id, :country
end
# used to generate a sane combination of instances for our models
def example_data
europe = Continent.new(:id => 1, :name => 'Europe')
asia = Continent.new(:id => 2, :name => 'Asia')
germany = Country.new(:id => 3, :name => 'Germany', :continent_id => 1, :continent => europe)
france = Country.new(:id => 4, :name => 'France', :continent_id => 1, :continent => europe)
china = Country.new(:id => 5, :name => 'China', :continent_id => 2, :continent => asia)
japan = Country.new(:id => 6, :name => 'Japan', :continent_id => 2, :continent => asia)
berlin = City.new(:id => 7, :name => 'Berlin', :country_id => 3, :country => germany)
cologne = City.new(:id => 8, :name => 'Cologne', :country_id => 3, :country => germany)
paris = City.new(:id => 9, :name => 'Paris', :country_id => 4, :country => france)
brest = City.new(:id => 10, :name => 'Brest', :country_id => 4, :country => france)
beijing = City.new(:id => 11, :name => 'Beijing', :country_id => 5, :country => china)
shanghai = City.new(:id => 12, :name => 'Shanghai', :country_id => 5, :country => china)
tokio = City.new(:id => 13, :name => 'Tokio', :country_id => 6, :country => japan)
osaka = City.new(:id => 14, :name => 'Osaka', :country_id => 6, :country => japan)
europe.countries = [germany, france]
asia.countries = [china, japan]
germany.cities = [berlin, cologne]
france.cities = [paris, brest]
china.cities = [beijing, shanghai]
japan.cities = [tokio, osaka]
{
:continents => [europe, asia],
:countries => [germany, france, china, japan],
:cities => [berlin, cologne, paris, brest, beijing, shanghai, tokio, osaka]
}
end
# setup is done, let's start with the fun part
e = example_data
@city = e[:cities][3]
puts grouped_collection_select(:city, :country_id, e[:continents], :countries, :name, :id, :name)
# outputs the following:
# <select id="city_country_id" name="city[country_id]">
# <optgroup label="Europe">
# <option value="3">Germany</option>
# <option value="4" selected="selected">France</option>
# </optgroup>
# <optgroup label="Asia">
# <option value="5">China</option>
# <option value="6">Japan</option>
# </optgroup>
# </select>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment