Collection_select not remembering selected value


#1

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


#2

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


#3

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