Saturday, 15 September 2012

ruby - Please explain form_for method in Rails -


This is not really a troubleshooting question, but there is a request for explanation. It is difficult to understand the work of form_for method. Can anyone tell me what is this method in this situation, to create a form for comment facility on the blog app here is my code. My code works, so I It is to understand why this works and how it works. Thanks !!

Here is my new comment form:

  and <% = form_for ([@ post, @ post.comments.build]) do | C | & Gt%; & Lt; P & gt; & Lt;% = c.label: Content, Category: "col-md control-label"%> & Lt; Br> & Lt;% = c.text_area: Content, Lines: "10", Category: "Form-Control"% & gt; & Lt; / P & gt; & Lt; P & gt; & Lt;% = c.submit% & gt; & Lt; / P & gt; & Lt;% end% & gt;  

And here is my code for the comments controller:

  class commentscontroller < ApplicationController def new @ post = post.id (params [: post_id]) Make the end deaf @ post = post.fund (param [: post_id]) @ comment = @ postcomments.cent (comment_arm) @ comment.user_id = current_user Id @ comment.save #redirect_to post_path (@ post) redirect_to posts_path end personal def comment_adam params.require (: comment) .permit (: content) end-end  

Specifically, what does Is there a form_for parameter for "[@ Post, @ post.comments.build]"?

First of all, you can not do anything with form_for You do not do ' form_tag (and some additional typing).

Allows you to form_for to easily create forms that fit in accordance with rail addendum URL and amp; Parameter naming The first argument for

form_for is the resource that is being edited or made. At its simplest it can be just @post . The array form is for namespace or nested resources.

Your [@ post, @ post.comments.build] means that this is a form of a new comment (the last element of the array is not a saved comment) That is nested under that particular post, as a result, post request must be made to / posts / 1234 / comments (ID is 1234 to handle the post).

The second thing form_for allows you to type in c.text_area: content . And it is to automatically use the correct parameter name (comment [content]) and it has the prefilled value with the current value of the comment content attribute.


No comments:

Post a Comment