Ruby on Rails Form有两个参数

时间:2014-07-18 02:01:23

标签: ruby-on-rails ruby

我有以下代码,但我无法理解如何为form_for([@ article,@ article.comments.build])进行路由。         

          的标题           <%= @ article.title%>         

    <p>
      <strong>Text:</strong>
      <%= @article.text %>
    </p>

    <h2>Add a comment:</h2>
    <%= form_for([@article, @article.comments.build]) do |f| %>
      <p>
        <%= f.label :commenter %><br>
        <%= f.text_field :commenter %>
      </p>
      <p>
        <%= f.label :body %><br>
        <%= f.text_area :body %>
      </p>
      <p>
        <%= f.submit %>
      </p>
    <% end %>

    <%= link_to 'Back', articles_path %>
    | <%= link_to 'Edit', edit_article_path(@article) %>

2 个答案:

答案 0 :(得分:3)

Rails可以暗示来自form_for

的路线

e.g。

<%= form_for(@article) do |f| %>
 ...
<% end %>

如果@article是新的而不在数据库中,那么rails可以推断出你正在创建一个新的,然后路由将是

articles_path(@article), action: :create

如果@article已存在于数据库中,那么rails可以推断出您正在编辑现有对象,因此路径为。

article_path(@article), action: :update

这适用于嵌套路由以及您拥有的示例代码。

<%= form_for([@article, @article.comments.build]) do |f| %>

它知道父路线是文章而子路线是评论,因为它是一个新评论,路线将是

article_comments_path(@article, @article.comments.build), action: :create

如果存在评论,那么它将是更新操作

article_comment_path(@article, @comment), action: :update

任何form_for,link_to等都可能暗示来自对象的路径。

答案 1 :(得分:2)

要做到这一点,你必须将你的评论路径嵌套在你的文章下面。所以你的溃败文件会有这样的东西

resources :article
  resources :comments
end

这会创建几个路径,这个路径就是

POST  /posts/:post_id/comments

在form_for帮助器form_for([@article, @article.comments.build])中告诉表单发布到该路径