Satya's blog - Ruby on Rails and option_groups

Jun 01 2009 22:47 Ruby on Rails and option_groups

Ruby on Rails rocks my socks again. I had a need for a drop-down with options from many "question sets". I did this in the controller:

@disclosure_questions=QuestionSet.find(:all,
        :conditions => ['is_screener=?', false], 
        :include => [:questions])

So QuestionSet was my outer collection, and each one has many questions, hence the include.

Then in my view I did this:
<select name="disclosure_id">
< option_groups_from_collection_for_select(
        @disclosure_questions, 'questions', 'title', 'id', 'number')
%>
<select>

Which says, make option groups from the disclosure_questions, which is a collection of QuestionSet. The sub-groups are composed of questions, which is a method called on each QuestionSet (by virtue of has_many). title is an attribute of QuestionSet, and id and number are attribute of each question.

More help at the Rails API site

Tag: rails