请在 Rails 中解释 form_for 方法

Please explain form_for method in Rails

这实际上不是一个故障排除问题,而是一个解释请求。我很难理解 form_for 方法的工作原理。有人可以向我解释这种方法在这种情况下的作用。这是我为博客应用程序的评论功能创建表单的代码。我的代码有效,所以我只想了解它为什么有效以及它是如何工作的。谢谢!!

这是我的新评论表:

<%= form_for([@post, @post.comments.build]) do |c| %> 
<p>
    <%= c.label :content, class: "col-md control-label" %><br> 
    <%= c.text_area :content, rows: "10", class: "form-control"  %>
</p> 

<p> 
    <%= c.submit %> 
</p> 

<% end %> 

这是我的评论控制器代码:

class CommentsController < ApplicationController 
    def new 
        @post = Post.find(params[:post_id])
    end 

    def create 
        @post = Post.find(params[:post_id]) 
        @comment = @post.comments.create(comment_params) 
        @comment.user_id = current_user.id 
        @comment.save 
        #redirect_to post_path(@post) 
        redirect_to posts_path 

    end 

    private 

    def comment_params 
        params.require(:comment).permit(:content)
    end
 end 

特别是form_for的“[@post,@post.comments.build]”参数有什么作用?

首先,form_for 可以做的事 form_tag 做不到(还有一些额外的输入)。

form_for 允许您轻松创建符合 rails 网址和参数命名约定的表单。

form_for 的第一个参数是正在编辑或创建的资源。最简单的情况下,这可能只是 @post。数组形式用于命名空间或嵌套资源。

您的 [@post, @post.comments.build] 示例表示这是嵌套在特定 post 下的新评论的表单(数组的最后一个元素是 Comment 的未保存实例)。这将导致表单向 /posts/1234/comments 发出 POST 请求(假设 post 的 ID 为 1234)。相应的嵌套路由需要存在才能工作。

form_for 为您做的第二件事是允许您编写 c.text_area :content 并自动使用正确的参数名称 (comment[content]) 并使用当前值预填充值评论的 content 属性。

form_for 会对特定资源执行 post 并帮助绘制输入。

示例 1

form_for(@post) 将对 myapp/posts/create 执行 post 并绘制 posts 字段

示例 2

form_for([@post, @post.comments.build]) 将对 myapp/posts/:post_id/comments/create 执行 post 并绘制评论字段

此处[@post,@post.comments.build]表示此表单用于新评论,表单将向/posts/post_id/comments发出POST请求(post_id 是一个@post.id)