0

I have a model Vendors which has many Products. I would like to add many Products at a time without showing the existing products that belong to the vendor.product relationship. I only want to display the form for new objects. Currently everything is working but on the add page I am getting all of the objects that are tied to the instance relationship which is @vendor.products. If I do not use that relationship in the form I do not get any fields.

Here is my new Product action:

'def new
    @vendor = Vendor.find(params[:vendor_id])
    5.times {@vendor.products.build}

  end'

Here is my form:

<%= form_for @vendor do |f| %>

  <%= f.fields_for :products do |g| %>
    <p>
     <%= g.label :name %>
     <%= g.text_field :name %>
     <%= g.label :category %>
     <%= g.select :category, options_for_select(['Parts', 'Labor', 'Extras', 'Shop']) %><br>
    </p>
  <% end %>
  <p><%= f.submit "Submit" %></p>
<% end %>

The Product Model:

class Product < ActiveRecord::Base
  belongs_to :vendors
  attr_accessible :name, :category, :vendor_id, :vendor_sku, :products
  validates :name, :uniqueness => true
  validates :category, :presence => true
  validates :name, :presence =>true
end

Just to reiterate, I would only like to show the blank, newly built objects as opposed to all of the products tied to that @vendor 's relationship. I must be overlooking a form structure to get this done but I just have not been able to figure it out. Thanks for looking.

1 Answer 1

1

Only render the nested fields if the product in a new record.

<%= form_for @vendor do |f| %>

  <%= f.fields_for :products do |g| %>
    <% if g.object.new_record? %>
      <p>
       <%= g.label :name %>
       <%= g.text_field :name %>
       <%= g.label :category %>
       <%= g.select :category, options_for_select(['Parts', 'Labor', 'Extras', 'Shop']) %><br>
      </p>
    <% end %>
  <% end %>
  <p><%= f.submit "Submit" %></p>
<% end %>
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! I wasn't aware of the new_record method.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.