2013-04-16 53 views
3

products_controller.rb導軌fields_for形式沒有顯示出來

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塊中呈現的原因以及爲什麼當我更改複數形式時它會呈現?

回答

7

想要很多折扣或一個折扣?

@product.build_discounthas_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 
+0

作出了改變。編輯部分正在索引上呈現。在索引操作中,我獲得了當前用戶的所有產品'@product = current_user.products'。添加'@ products.discounts.build'會引發未定義的方法「折扣」錯誤。 –

+0

我正在更新我的答案。 –

0

你如何通過局部變量product_edit_product.html.erb部分?我猜你有一個new.html.erb視圖,你渲染你的部分?

+0

我上面的評論回答了這個問題。謝謝。 –

+0

您在此處將'@ product'的產品集合分配給@ @@@@@ @產品= current_user.products',然後引用'@products'(據我所知,根本不存在)這裏'@products.discounts .build'。 – Brett

0

使用@ mind_blank的回答,我寫了這個解決方案:

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

形式的此行之後出現了。