Nageshwari P
Nageshwari P

Reputation: 35

Set selected value on edit in Rails forms

i need to get selected value on select tag on edit.

i have form select field like this.

<%= f.select :city,  options_from_collection_for_select(@cities, 'id', 'name',@city),{}, {:class=>'form-control',:'data-validation'=>"required",:'data-validation-error-m‌​sg'=>"Select City"} %>

in my controller on edit i did like this:

def edit
 @cities=City.all
 @p = Property.find(params[:id])
 @[email protected]
end

when i try to print like this <%= @city %> in my edit form , it is getting the selected value from database. But when i try to give in select field it is not reflecting. Please help.

Any help is appreciatable

Upvotes: 2

Views: 5039

Answers (4)

Juan Nicolas
Juan Nicolas

Reputation: 11

I just solved like this

<%= form.select :product_id, options_from_collection_for_select(Product.where(:active => true), :id, :name, item.product_id), {}, {class: "form-select"} %>

Upvotes: 0

Buck3000
Buck3000

Reputation: 371

I think this should do it:

<%= f.select :city,  options_from_collection_for_select(@cities, 'id', 'name',@city), {selected: @city.id}, {:class=>'form-control',:'data-validation'=>"required",:'data-validation-error-m‌​sg'=>"Select City"} %>

Basically, if you add {selected: @city.id} to the hash after the options_from_collection_for_select it should work. The select method is a bit funky.

Upvotes: 1

Alex.U
Alex.U

Reputation: 1701

Have you checked collection_select ? Something like:

f.collection_select :city, :city_id, @cities, :id, :name

Anytime you create/edit a new object the form's builder will populate the select with the object's value (in case there is an object); this is, will set the selected attribute - or simply populate the select if you're creating a new object.

Upvotes: 1

Emu
Emu

Reputation: 5905

<%= f.select :city, options_for_select(@cities.collect{|city| [city.name, city.id]}, @city), :prompt => "Select One", :class => 'form-control' %>

Hope this helps! You can see options_for_select

Upvotes: 1

Related Questions