Forum: Ruby on Rails collection_select not remembering selected value

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
8ee257799a0f1898dd1951bd2843bc71?d=identicon&s=25 Eric Marthinsen (emarthinsen)
on 2009-01-02 08:57
(Received via mailing list)

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

<%= 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?

8ee257799a0f1898dd1951bd2843bc71?d=identicon&s=25 Eric Marthinsen (emarthinsen)
on 2009-01-02 09: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.

8ee257799a0f1898dd1951bd2843bc71?d=identicon&s=25 Eric Marthinsen (emarthinsen)
on 2009-01-02 09: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.

This topic is locked and can not be replied to.