Rails 5 - 为具有 has_many 关系的“文章”创建“评论”

tac*_*tac 4 ruby-on-rails ruby-on-rails-5

我的问题是关于官方Rails 指南的第 6.4 节

我有一篇文章和一个评论模型,它们之间有 has_many 关系。现在,我们编辑文章显示模板 (app/views/articles/show.html.erb),让我们为每篇文章添加新评论:

<p>
  <strong>Title:</strong>
  <%= @article.title %>
</p>

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

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

<%= link_to 'Edit', edit_article_path(@article) %> |
<%= link_to 'Back', articles_path %>
Run Code Online (Sandbox Code Playgroud)

有人可以 ELI5 form_with 声明吗?

form_with(模型:[@article,@article.comments.build],本地:真)

我知道必须为特定文章创建每个评论,并且指南中的描述还提到form_with此处的调用使用数组,但为什么我们需要将数组传递给模型:?为什么我们在数组中有两个成员?如果我们只是传递@article.comments给模型怎么办:.build与 中@article.comments.create使用的调用相比,函数调用的意义是什么comments_controller.rb

bar*_*mic 6

Rails 从form_with. 让我们考虑这个案例:

<%= form_with(@article) do |f| %>
 ...
<% end %>
Run Code Online (Sandbox Code Playgroud)

当文章是新的,并且在数据库中不存在时,Rails 会推断出该路线是:

articles_path(@article), action: :create
Run Code Online (Sandbox Code Playgroud)

因为你正在创造一个新的。

如果数据库中存在文章,Rails 会生成更新路由:

articles_path(@article), action: :update
Run Code Online (Sandbox Code Playgroud)

因此,数组意味着该路径将被嵌套。所以,这段代码:

<%= form_with([@article, @article.comments.build]) do |f| %>
 ...
<% end %>
Run Code Online (Sandbox Code Playgroud)

如果评论在数据库中不存在,则生成此路线:

article_comments_path(@article, @article.comments.build), action: :create
Run Code Online (Sandbox Code Playgroud)

否则,路线将是:

article_comments_path(@article, @comment), action: :update
Run Code Online (Sandbox Code Playgroud)

更多关于new和之间的区别build在 Rails 上构建和新建有什么区别?

更多关于form_for,form_withhttps://m.patrikonrails.com/rails-5-1s-form-with-vs-old-form-helpers-3a5f72a8c78a 的比较form_tag

  • 是的,这是一个错字,应该是“form_with”。谢谢。关于 article_comments_path(@article, @article.comments.build):它会生成这样的路径:/articles/@article.id/comments(POST 请求) (2认同)