Setting a default option for a select list of a new object

Yet another Rails newby getting his feet wet…

I have a lookup table for states in a database that I use to create a
select list for objects with addresses.

When creating a new object (a business, in this case), I want the
“State” select field to automatically have, say, Idaho selected. How
do I do that? Here’s my code so far:

Business Controller

def new
@business = Business.new
@states = State.find(:all) # so the _form partial can
create the select list
end

Business Model

belongs_to :state #set up the relationship between Businesses
and States

_form partial

<%= select_tag(‘state_id’, options_for_select(@states.collect {|s|
[s.name, s.id]}, @business.state_id)) %>

The @business.state_id will select the state for a business that
already exists when this _form partial is used in the edit view. I
want to have a default state selected (Idaho) for NEW businesses that
isn’t the first one in the list (Alabama).

Hi,

an obvious answer to this would be to have one variable collecting the
State object for Idaho, and one collecting all states. To make it
more dynamic, maybe it’s better to leave the state as a session
variable, or a global variable, or something stored in an object
expressing local preferences …

@local = State.find_by_name(“Idaho”)
@states = State.find(:all)

then, in the form
<%=
options = [[@local.name],[@local.id]] + @states.collect{|s|
[s.name,s.id]}
select(“state”,“id”,options)
%>
(you could maybe add a separator between the local state and the full
list of state
[["--------",""]] or similar)

Elise

I’m wondering if there’s a way to use the initialize method of the
BusinessModel to achieve the desired result…