Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

  1. 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 new one only.
  2. 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?

like image 397
Alex Avatar asked Jan 21 '23 16:01

Alex


1 Answers

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 %>
like image 61
Celso Dantas Avatar answered Jan 31 '23 03:01

Celso Dantas