ruby-on-rails - 错误处理多模型表格

标签 ruby-on-rails error-handling multi-model-forms

我有一个多模型表单,但似乎无法捕获与嵌套模型有关的错误。这是形式Project-> Team-> Roles-> Role_skill_relationship的层次结构。我能够捕获与项目模型实例@project有关的错误,但是在捕获与角色和技能模型有关的验证方面,我一直没有成功。错误会直接在浏览器页面中返回,而不是重定向并闪烁到屏幕。如果我有意不正确地填写了表格的角色部分,则会出现一个错误示例:

NoMethodError in Roles#create

Showing C:/Users/Dstile/Documents/GitHub/creunity_app/app/views/skills/_form.html.erb where line #8 raised:

undefined method `map' for nil:NilClass Extracted source (around line #8)

7: <%= skill_form.label :skill %>
8: <%= skill_form.collection_select :skill_id, @skills, :id, :name, :prompt => "Select a > skill" %>



这是代码的一部分
<%= render 'shared/project_error_messages' %>

    <%= project_form.label :title %>
    <%= project_form.text_field :title %>

    <%= project_form.label :category, "Category" %>
    <%= project_form.select(:category, Project::CATEGORY_TYPES) %>

    <%= project_form.label :description %>
    <%= project_form.text_area :description %>

    <%= project_form.label :goal_1, "Goal 1:" %>
    <%= project_form.text_field :goal_1 %>

    <h2>Your Team</h2>
    <%= project_form.fields_for :team do |f| %>
      <%= render 'teams/form', :team_form => f %>
    <% end %>`

这是错误渲染代码
'<% if @project.errors.any? %>
  <div id="error_explanation">
    <div class="alert alert-error">
      The form contains <%= pluralize(@project.errors.count, "error") %>.
    </div>
    <ul>
    <% @project.errors.full_messages.each do |msg| %>
      <li>* <%= msg %></li>
    <% end %>
    </ul>
  </div>
<% end %>'

角色表单嵌套在团队表单中,就像团队嵌套在项目中一样。从所有其他线程中,我已经了解到我的理解是,项目及其所有子模型(团队,角色,role_skill_relationships)的错误应由@parent对象捕获。

是否有配置设置或我缺少的代码片段会迫使浏览器忽略错误?我的想法是错误可能在@project中,但是该过程被中断了。

最佳答案

似乎@skills尚未设置。 #collection_select在传入的集合上运行#map(在这种情况下为@skills),如果该集合是nil(这是未定义实例变量的默认值),则会显示该错误。

请记住,如果发生验证错误,则 Controller 中的#create方法将仅呈现模板-它不会为该模板运行相应的action方法。因此,如果要在@skills操作中定义#new,则还需要在#create操作中定义它(或者更好的是在before_filter中定义)。

关于ruby-on-rails - 错误处理多模型表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14088468/

相关文章:

r - biotools R封装中的boxM测试

ruby-on-rails - 收集抛出的RoutingError消息

django-forms - 通过选项卡按钮删除不起作用

mysql - Rails 4 连接远程 MySQL 数据库并拉取数据库结构以便于访问

sql - 优化困难查询(可能使用 squeel)

javascript - WebApi 捕获连接超时错误

python - 编辑 django 表单小部件渲染

ruby-on-rails - 如何在多模型形式中使用 error_messages_for ?

ruby-on-rails - 表格列宽不增加

mysql - Rails Simple_Form 在数据库中将值保存为 NULL