2010-08-02 61 views
2

我有我的Rails應用程序中的模型產品,其屬性可以編輯,我想讓用戶評論他所做的每一個變化(儘管評論可以是空白的)。因此,產品has_many:評論,它accept_nested_attributes_for:評論,並拒絕它,如果評論是空白的。Rails:fields_for只有一個對象

因此,產品的編輯表單是一種多模式表單。我遇到的問題有:

  1. Fields_for helper呈現屬於該產品的所有評論的文本區域,因此用戶可以編輯以前的所有評論。我需要它只爲新的字段渲染字段。
  2. 如果驗證中斷,並且沒有任何評論,fields_for不呈現任何內容。我應該每次在fields_for語句之前在視圖中執行@ product.comments.build,還是有更優雅的方法來執行此操作?

也許我錯了,fields_for不適合這種情況?

回答

0
<% f.fields_for(:comments, Product.reflect_on_association(:comments).klass.new) 
    do |builder| %> 

    <%= builder.label :comment %> 
    <%= builder.text_area :comment, :rows => 3 %> 
<% end %> 
6

基礎上TOTS回答我只是做了一點simplier(Rails 3的兼容):

<%= f.fields_for :comments, @product.comments.build do |comment| %> 
    <%= comment.label :comments %><br /> 
    <%= comment.text_area :content %> 
<% end %> 
+0

這個答案應標記爲正確的! – ClassyPimp 2015-04-06 13:45:39