0

Here is my haml code:

-if params[:product_id]
  =select_tag 'product',
              options_from_collection_for_select(Product.all, :id, :name),
              placeholder: "Product", required: true,
              value: Product.find(params[:product_id]).name
-else
  =select_tag 'product',
              options_from_collection_for_select(Product.all, :id, :name),
              :prompt => 'Select', placeholder: "Product", required: true

The problem is that the value is good when I inspect the element :

<select id="product" name="product" placeholder="Product" required="required" value="Product 2">
        <option value="1">Product 1</option>
        <option value="2">Product 2</option>
        <option value="3">Product 3</option></select>

Even if that seams good, the select hasn't is value at "Product 2", the value of the element, yes, but the selected value is "Product 1".

I don't know why and I'm sure I'm messing with something x)

EDIT:

value: Product.find(params[:product_id]).id
value: Product.find(params[:product_id]).id.to_i

This kind of changes doesn't change anything in the problem

Charlon
  • 363
  • 2
  • 16

1 Answers1

0

When you pass through the value option it is matched against the value attributes of the option tags, NOT their contents.

Try changing the value option to

value: params[:product_id].to_i

EDIT: just realised that the pre-selected value needs to be passed through as the last option to options_from_collection_for_select:

=select_tag 'product',
          options_from_collection_for_select(Product.all, :id, :name, params[:product_id].to_i),
          placeholder: "Product", required: true

http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html

Max Williams
  • 32,435
  • 31
  • 130
  • 197