簡體   English   中英

請在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允許您使用urls和參數命名輕松創建符合rails約定的表單。

form_for的第一個參數是正在編輯或創建的資源。 最簡單的可能就是@post 數組表單用於命名空間或嵌套資源。

你的[@post, @post.comments.build]例子意味着這是一個新注釋的表單(數組的最后一個元素是未保存的Comment實例),它嵌套在該特定帖子下。 這將導致表單對/posts/1234/comments發出POST請求(假設帖子的id為1234)。 需要存在相應的嵌套路由才能使其生效。

form_for為您做的第二件事是允許您編寫c.text_area :content並自動使用正確的參數名稱(comment [content])並使用注釋的content屬性的當前值預先c.text_area :content該值。

form_for將對特定資源發布帖子並幫助繪制輸入。

例1

form_for(@post)發帖myapp/posts/create並繪制帖子字段

例2

form_for([@post, @post.comments.build])發帖myapp/posts/:post_id/comments/create並繪制評論字段

這里[@ post,@ post.comments.build]表示此表單用於新注釋,表單將對/ posts / post_id / comments執行POST請求(post_id是@ post.id)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM