Select in form_for in Rails 3

Posted on July 11, 2011

0


I have often been confused about form helpers in rails.
Recently I was doing a project in which I had to use select tag.
So finally after spending a lot of time on this trivial things I figured it out.
Its very simple….lemme explain (or I must say lemme show u how stupid I was !! ) with a code.

assume that I have a form_for tag and I have a object (@question) which has an attribute like type_id:
The select tag for the same will be

   <%= f.select “type_id”,Type.all.collect{|t|[t.name,t.id]} %>

This will ofcourse be in the view.

Type is a table in my database.

In the controller I can access the value of this field as

params[:question][:type_id]

In the above form field what gets passed in the params is id of the Type table and what gets displayed is name in the type table.
So if an entry in Type table looks like

1        MCQ

then MCQ will be displayed in the form and when submit button is pressed the value passed will be 1

This saved my day !!

Advertisements
Posted in: Rails app