This is a preamble to the last years post Building a Cascading Drop Down Selection List for Ruby on Rails with jQuery Ajax, In part because I’ve realized that people where are lost without some basic setup I assumed as given. So here I’m giving it, explicitly.
Directions here are valid for Ruby 1.8, Ruby on Rails 2.3.5 and jQuery 1.4.2, and I still going for “The Simplest Thing That Will Work” (TSTTWW)
First generate scaffolding for Section (with name as columns) and Sub_Section (with name and section_id as columns)
>script/generate scaffold Sections name:string
>script/generate scaffold Sub_Sections name:string section_id:integer
Then run Migration to create these 2 tables in your database
>rake db:migrate
Modify the models to account for the association between the model and very basic validation
class Section < ActiveRecord::Base
has_many :sub_section
validates_presence_of :name
end
class SubSection < ActiveRecord::Base
belongs_to :section
validates_presence_of :name, :section_id
end
Modify the Sub_section New view to allow the selection of a Section name and the population of the model with a valid Section Id, but blank by default
< %= f.label :section_id %>
< %= collection_select(:sub_section, :section_id, Section.all, :id, :name , options ={:prompt => ""} ) %>
the edit view needs to modified as well to show the selected value but allow you to change it
< %= f.label :section_id %>
< %= collection_select(:sub_section, :section_id, Section.all, :id, :name ) %>
Modify the Sub_section index view to show the Section Name’s
and Modify the Show view as well it include the section name
Section Name:
< %=h @sub_section.section.name %>
So now things are setup to populate the Sections and SubSection by adding (for example Sections : Meat,
Vegetables, Fruit) and Subsections {Beef, Meat} and {Apple , Fruit}, {Pork, Meat}, etc…..
Which can be used elsewhere like a Gallery model, viewer and controler
>script/generate scaffold Gallery name:string section_id:integer sub_section_id:integer
run Migration to create this table in your database
>rake db:migrate
change the Gallery model to add the association for Section_id and sub_section_id field and add the validation
belongs_to :section
belongs_to :sub_section
validates_presence_of :name, :section_id, :sub_section_id
Add Jquery to the public/javascript library and Modify the layout of Gallery to include it in your views foe test with
< %= javascript_include_tag 'jquery-1.4.2.min.js' %>
from there the directions on the orginal post Building a Cascading Drop Down Selection List for Ruby on Rails with jQuery Ajax apply.
Update : a April 2015 article is a worthy update : Dynamic Duos – Dependent Select Menus with JQuery and Rails (and links back to the orginal post!)
Pingback: Building a Cascading Drop Down Selection List for Ruby on Rails with jQuery Ajax | False Positives