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
折扣.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
block 中的内容不显示。但是,如果我将 has_many :discounts
更改为 has_many :discount
,则会显示该表单(尝试提交时出现质量分配错误)。
关于为什么在 fields_for
block 中不呈现表单以及为什么在我更改复数形式时它呈现的任何想法?
最佳答案
您想要许多折扣还是一个折扣?
@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
关于ruby-on-rails - Rails fields_for 表单未显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16027066/