Forum: Ruby on Rails collection_select not remembering selected value

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.
Eric M. (Guest)
on 2009-01-02 09:57
(Received via mailing list)
Hello-

I have a form that I'm using form_for on to bind the form to my order
object. Within the form, I want to select a product (each order has
one product, which makes this easy). In my order and product models,
an order belongs_to a product. I didn't specify that a product
has_many orders (although I did test that the problem still exists
even if I do specify that). Here's the code I'm using to generate the
select list:

@packages = Package.find(:all, :order => 'name') #this is in my
controller

<%= f.collection_select :product, @products, :id, :name, { :prompt =>
'--select one--'} %>

The call to collection_select creates the list of options just fine,
but if my order has a value set for product, it doesn't get set as the
selected value.

I've tried a slew of other variations on the call to collection_select
(e.g., using :product_id instead of :product) and all seem to fail.

Does anyone know what I might be doing wrong?

Regards,
Eric
Eric M. (Guest)
on 2009-01-02 10:07
(Received via mailing list)
One more thing. I debugged my app and when I inspect my @order object,
the product field is being correctly set. I debugged a little deeper
and it looks like at some point, Rails is trying to decide to set a
particular option to selected by evaluating something like the
following (assuming product id 7 was selected):

"7" == 7

It looks like, for the purpose of setting my model's attributes, the
product id is being turned into an integer, but for selecting a value
in collection_select, it is keeping it a string. Very confusing.

-Eric
Eric M. (Guest)
on 2009-01-02 10:28
(Received via mailing list)
Ah ha, I figured it out. In my migration, I had accidentally specified
that the product_id column should be a string, instead of an integer.
Once I changed the type, everything worked great.

Regards,
Eric
This topic is locked and can not be replied to.