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 %>

fields_for块中的内容未显示。 但是,如果我将has_many :discounts更改为has_many :discount ,则表单显示(当我尝试提交时获取批量分配错误)。

关于为什么表单不在fields_for块中呈现以及为什么在我更改复数时它会呈现的任何想法?

===============>>#1 票数:7 已采纳

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

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

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

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

f.fields_for :discount do |discount_form| accepts_nested_attributes_for :discount单数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

===============>>#2 票数:0

你如何将局部变量product传递给_edit_product.html.erb部分? 我猜你有一个new.html.erb视图,你在哪里渲染你的部分?

===============>>#3 票数:0

使用@ mind_blank的答案,我写了这个解决方案:

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

表格出现在此行之后。

  ask by rabid_zombie translate from so

未解决问题?本站智能推荐: