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
块中呈现以及为什么在更改复数时它会呈现的任何想法?
答案 0 :(得分: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
答案 1 :(得分:0)
如何将局部变量product
传递给_edit_product.html.erb
部分?我猜你有一个new.html.erb
视图,你在哪里渲染你的部分?
答案 2 :(得分:0)
使用@ mind_blank的答案,我写了这个解决方案:
@products = current_user.products.each {|product| product.discounts.build}
该表格出现在此行之后。