【发布时间】:2020-10-26 14:03:04
【问题描述】:
这里是 Rails“入门”指南 (https://guides.rubyonrails.org/getting_started.html) 中的 form_with 视图助手,用于嵌套文章模型 Comment 或 Article.comments:
<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 %>
还有
class Article < ApplicationRecord
has_many :comments
validates :title, presence: true,
length: { minimum: 5 }
end
和
class Comment < ApplicationRecord
belongs_to :article
end
现在我想知道是否可以使用 form_with 助手或其他助手或助手组合来创建或编辑具有多个嵌套模型的新文章,例如评论、标签、 ...以及文章可以由哪些进一步的模型组成。
...它创建了一个理智且有用的参数哈希(因为我自己的带有“fields_for”表单助手的解决方案不会产生所需或有用的参数哈希。
这就是 params-hash 的样子:
<ActionController::Parameters {"utf8"=>"✓", "_method"=>"patch", "authenticity_token"=>"BeCtYS/U6lugXzzplTEBsMXAiD0x7z28iBUblHiza379p4YqRcd+ykgd49o53oOrC8o+iPhtWnvQQHe0ugCJow==", "article"=>{"parent_article_id"=>"", "title"=>"Überschrift", "text"=>"Toller Text"}, "tags"=>{"name"=>"Rails"}, "commit"=>"Update Article", "controller"=>"articles", "action"=>"update", "id"=>"1"} permitted: false>
问题在于控制器/文章 ID 未包含在 :article 键下。我不知道如何为 strong_parameters 解决这个问题,我什至不想这样做。我更希望 Rails 只是按照最小惊讶原则运行,而不是做一些骇人听闻的事情来让事情正常运行。
在这种情况下,我希望是我自己对表单助手的无知和缺乏知识导致 Rails 无法生成正确的 params-hash。
谢谢。
【问题讨论】:
-
我想你在找
accepts_nested_attributes_for,也就是here -
谢谢,但已经添加到我的模型中
-
accepts_nested_attributes确实在父母的“孩子”模型参数中嵌套,所以你应该得到你所要求的。您可以发布自己的视图和控制器代码吗?你的参数看起来很奇怪,我猜你没有正确实现表单。
标签: ruby-on-rails strong-parameters view-helpers