3

products_controller.rb

def new
  @product = Product.new
  @product.build_discount
end

product.rb

has_many :discounts, :dependent => :destroy
accepts_nested_attributes_for :discounts
attr_accessible :discounts_attributes

discount.rb

belongs_to :product

_edit_product.html.erb

<%= form_for(product, :html => { :multipart => true  }, :remote => true) do |f| %>
    // STUFF
    <%= f.fields_for :discounts do |discount_form| %>
       //does not show up
    <% end %>
<% end %>

The content in the fields_for block does not show up. However, if I change has_many :discounts to has_many :discount, the form shows up (get mass assignment error when I try to submit).

Any ideas as to why the form is not rendering in the fields_for block and why it does render when I change the pluralization?

3 Answers 3

7

Do you want many discounts or one discount?

@product.build_discount is used in a has_one association, but the rest of your code is for has_many

If you want many discounts then change it to @product.discounts.build

Otherwise, if you want just one discount, change the following:

f.fields_for :discount do |discount_form| and accepts_nested_attributes_for :discount to singular.

@products.discounts.build won't work because you can't get an association from a collection of objects. For example:

@products = Product.all
@discount = @products.discounts.build
# This won't work! You'll get an error

@product = Product.find(params[:id])
@discount = @product.discounts.build
# This will work, since you're running it on a single instance of Product
1
  • Made that change. The edit partial is being rendered on index. In the index action, I get all the products of the current user '@product = current_user.products'. Adding '@products.discounts.build' throws an undefined method "discounts" error. Commented Apr 16, 2013 at 1:39
0

How are you passing the local variable product to your _edit_product.html.erb partial? I'm guessing you have a new.html.erb view where you render your partial?

2
  • My comment above answers this question. Thanks. Commented Apr 16, 2013 at 1:39
  • You're assigning a collection of products to @product here @product = current_user.products, then referencing @products (which as far as I can tell, doesn't exist) here @products.discounts.build.
    – Brett
    Commented Apr 16, 2013 at 1:50
0

Using @mind_blank's answer, I wrote this solution:

@products = current_user.products.each {|product| product.discounts.build}

The form showed up after this line.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.