Forum: Ruby on Rails Setting a default option for a select list of a new object

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
829f2eef24c244ea33165adde8bd36d5?d=identicon&s=25 partydrone (Guest)
on 2007-05-20 08:46
(Received via mailing list)
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).
1f36de0ab637612b390bbc4ac52b0b80?d=identicon&s=25 huard.elise@gmail.com (Guest)
on 2007-05-20 10:00
(Received via mailing list)
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
829f2eef24c244ea33165adde8bd36d5?d=identicon&s=25 partydrone (Guest)
on 2007-05-21 03:15
(Received via mailing list)
I'm wondering if there's a way to use the initialize method of the
BusinessModel to achieve the desired result...
This topic is locked and can not be replied to.