Rails: fields_for only one object
I've got a model Product in my Rails application, its attributes can be edited, and I want to let user comment every change he makes (a comment can be blank, though). So, Product has_many :comments, it accepts_nested_attributes_for :comments and rejects it if the comment is blank.
Hence, the edit form for Product is a multi-model form. The problems I faced are:
- Fields_for helper renders text areas for all comments belonged to the product, so the user can edit all previous comments. I need it to render fields for the ne开发者_Python百科w one only.
- If validation breaks, and there are no comments, fields_for renders nothing. Should I perform @product.comments.build in the view before fields_for statement every time, or there is more elegant way to do it?
Maybe I'm wrong and fields_for isn't suitable in this situation?
Base on Tots answer I just made it a little simplier (Rails 3 compatible):
<%= f.fields_for :comments, @product.comments.build do |comment| %>
<%= comment.label :comments %><br />
<%= comment.text_area :content %>
<% end %>
<% f.fields_for(:comments, Product.reflect_on_association(:comments).klass.new)
do |builder| %>
<%= builder.label :comment %>
<%= builder.text_area :comment, :rows => 3 %>
<% end %>
精彩评论