a preamble to Building a Cascading Drop Down Selection List for Ruby on Rails with jQuery Ajax

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)

1
2
3
>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

1
>rake db:migrate

Modify the models to account for the association between the model and very basic validation

1
2
3
4
5
6
7
8
9
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

1
2
3
4
  <p>
    < %= f.label :section_id %><br />      
    < %=  collection_select(:sub_section, :section_id, Section.all, :id, :name , options ={:prompt => ""} ) %>
  </p>

the edit view needs to modified as well to show the selected value but allow you to change it

1
2
3
4
  <p>
    < %= f.label :section_id %><br />        
    < %=  collection_select(:sub_section, :section_id, Section.all, :id, :name ) %>
  </p>

Modify the Sub_section index view to show the Section Name’s

1
    <td>< %=h sub_section.section.name %></td>

and Modify the Show view as well it include the section name

1
2
3
4
<p>
    <b>Section Name:</b>
    < %=h @sub_section.section.name %>
</p>

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

1
>script/generate scaffold Gallery name:string section_id:integer  sub_section_id:integer

run Migration to create this table in your database

1
>rake db:migrate

change the Gallery model to add the association for Section_id and sub_section_id field and add the validation

1
2
3
  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

1
  < %= 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.

Leave a Reply