Mahesh Mesta Mahesh Mesta - 2 months ago 23
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
end

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

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


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 %>
</div>
<% end %>


My _product_fields.html.erb is

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


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
end


My vendor controller is here

def new
@vendor = Vendor.new
@vendor.vendor_products.build
end

def edit
@vendor.vendor_products.build
end


The vendor and the
VendorProduct
which contains
Product_id
and
Vendor_id
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

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

<%= f.select :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