- if params[:item] # we are dealing with a form with validation errors so fill in the last known value for sub_category
= f.select :sub_category_id, options_for_select(@options_for_sub_category, params[:item][:sub_category_id]), {}, :class => 'required'
- elsif params[:uuid] # an edit action
= f.select :sub_category_id, options_for_select(@options_for_sub_category, @item.sub_category_id), {}, :class => 'required'
- else # a new action
= f.select :sub_category_id, '', {}, :class => 'required'
# where @options_for_sub_category is a class methos to retrieve the sub_categories based on the value of category.
Refactorings
No refactoring yet !
Adam
October 29, 2010, October 29, 2010 00:27, permalink
FormBuilder#select will automatically create the <option> tags from the array input, no need to call options_for_select. It will also automatically select the selected value based on the value stored in the model.
class ItemsController < ApplicationController
before_filter :set_options_for_sub_category, :only => [ :edit, :create ]
def new
@item = Item.new
end
def edit
@item = Item.find(params[:id])
end
def create
@item = Item.new(params[:item])
end
private
def set_options_for_sub_category
@options_for_sub_category = Options.sub_categories
end
end
= form_for(@item) do |f|
= f.select :sub_cateogry_id, @options_for_sub_category, {}, :class => 'required'
I have a select tag in my view that gets populated via ajax based on the value of another select tag. This is fine for a new action as the select_tag is unpopulated, however, if I have a validation error (which re-renders the view) or an edit action then I need to re-populate the select tag with the value the user chose.