ruby on rails 3 - `accepts_nested_attributes_for`, but only modify the first child -


a brief background

i'm making conventional forum learn/practice rails.

user model   has_many :topics   has_many :posts  topic model   has_many :posts   belongs_to :user  post model   belongs_to :user   belongs_to :topic 

however, when user creating new topic, want them simultaneously create first post within topic (just forums work). additionally, when topic creator edits topic, edits first post.

so, added accepts_nested_attributes_for :posts topic model.

# topiccontroller def new   @topic = current_user.topics.new   @topic.posts.build end 

and here's nested form:

# topics/_form <%= form_for [@topic] |topic| %>   <%= topic.text_field :name %>   <% topic.fields_for :posts |post| %>     <%= post.text_area :content %>   <% end %> <% end %> 

the question

this code works. user create first post alongside creation of topic.

however, other users create posts topic , @topic.posts expands, when topic creator edits topic, text areas every post in topic appear editable topic creator.

how can make topic creator can see , edit first post of topic on views/topics/_form form??

helpful resource: http://apidock.com/rails/actionview/helpers/formhelper/fields_for

created new partial alongside topics/_form called _edit_form topics#edit action.

reading api doc (go figure), found can specify instance forms_for:

<%= form_for @topic |f| %>   <%= f.error_messages %>   <p>     <%= f.label :name %><br />     <%= f.text_field :name %>   </p>   <p>     <%= f.fields_for :posts, ---->@post<---- |p| %>         <%= p.text_area :content %>     <% end %>   </p>   <p><%= f.submit %></p> <% end %> 

in topics controller:

def edit   @topic = ...   @post = @topic.posts.first end 

Comments

Popular posts from this blog

c# - how to write client side events functions for the combobox items -

exception - Python, pyPdf OCR error: pyPdf.utils.PdfReadError: EOF marker not found -