Mahesh Mesta Mahesh Mesta - 1 year ago 108
Ruby Question

Collection Select not displaying the selected value in edit form for rails 4

I have a Vendor model, a Product model and a VendorProduct model with the following association

class Vendor < ActiveRecord::Base
has_many :vendor_products
has_many :products, through: :vendor_products

class Product < ActiveRecord::Base
has_many :vendor_products
has_many :vendors, through: :vendor_products

class VendorProduct < ActiveRecord::Base
belongs_to :vendor
belongs_to :product

I am using nested_form gem to display a dropdown collection select option for products on my vendor _form.html.erb page

<%= nested_form_for(@vendor) do |f| %>
<% if @vendor.errors.any? %>
<%= f.fields_for :vendor_products do |vproducts| %>
<%= render 'product_fields', :f => vproducts %>
<%= vproducts.link_to_remove "Remove this Product" %>
<% end %> &nbsp
<%= f.link_to_add "Add product", :vendor_products %>

<div class="actions">
<%= f.submit %>
<% end %>

My _product_fields.html.erb is

<div class= "vendor_products">
<div class="field">
<%= f.label :product_id %><br>
<%= :product_id,
options_from_collection_for_select(Product.all, "id",
"product_name"), prompt: "Select something", %>
<%= f.label :copies %>
<%= f.number_field :copies %>

My Vendor model has the following accepted_nested_attributes for vendor_products

class Vendor < ActiveRecord::Base
accepts_nested_attributes_for :vendor_products, :allow_destroy =>
true, :reject_if => :all_blank

My vendor controller is here

def new
@vendor =

def edit

The vendor and the
which contains
gets populated correctly. All works well, the only problem is that in the vendors edit page, the product select option does not displays the selected value but rather the first option in the drop down list. However when I check my value for the row, the correct product has been added to the table.Only the edit page drop down does not shows the actually selected value.

How can I fix this? Please help.

Answer Source

This is the issue with nested_attributes and dropdown

You can make use of form object "f" to get :product_id using f.object.product_id and pass it as selected value

<%= :product_id,
              options_from_collection_for_select(Product.all, "id", "product_name", f.object.product_id), 
              prompt: "Select something" %>

Refer options_from_collection_for_select

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download