Rails fields_for表单没有显示

rab*_*bie 3 ruby ruby-on-rails ruby-on-rails-3

products_controller.rb

def new
  @product = Product.new
  @product.build_discount
end
Run Code Online (Sandbox Code Playgroud)

product.rb

has_many :discounts, :dependent => :destroy
accepts_nested_attributes_for :discounts
attr_accessible :discounts_attributes
Run Code Online (Sandbox Code Playgroud)

discount.rb

belongs_to :product
Run Code Online (Sandbox Code Playgroud)

_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 %>
Run Code Online (Sandbox Code Playgroud)

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?

min*_*ank 7

你想要很多折扣或一个折扣吗?

@product.build_discount用于has_one关联,但其余代码用于has_many

如果您想要很多折扣,请将其更改为@product.discounts.build

否则,如果您只想享受一次折扣,请更改以下内容:

f.fields_for :discount do |discount_form|accepts_nested_attributes_for :discount单数.

@products.discounts.build将无法工作,因为您无法从对象集合中获取关联.例如:

@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
Run Code Online (Sandbox Code Playgroud)