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).