【问题标题】:Ruby on Rails form errors not displayingRuby on Rails 表单错误未显示
【发布时间】:2018-12-20 18:28:05
【问题描述】:

我正在创建一个基本应用程序来创建和存储要练习的食谱,并且似乎无法在我的表单下显示错误,下面是我所拥有的简单示例 -

recipes_controller.rb(相关部分)

def new
  @recipe = Recipe.new
end

def create
  @recipe = Recipe.new(recipe_params)
  @recipe.save
  redirect_to '/create_recipe'
end

private  
def recipe_params
  params.require(:recipe).permit(:title, :description)
end

recipe.rb(模型)

class Recipe < ApplicationRecord
    has_many :ingredients
    has_many :steps

    validates_presence_of :title
end

new.html.erb

<%= form_for @recipe do |f| %>
    <div class="new_recipe_form">

      <% if @recipe.errors.any? %>
        <div class="form_error">
          <ul>
            <% @recipe.errors.full_messages.each do |msg| %>
              <li><%='Error: ' +  msg %></li>
            <% end %>
          </ul>
        </div>
      <% end %>

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

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

    </div>

    <div>
      <%= f.submit %>
    </div>
<% end %>

当我提交没有标题的表单时,什么也没有发生。它不会创建配方,所以我知道验证器正在工作,但没有出现错误。

任何帮助将不胜感激。

【问题讨论】:

    标签: ruby-on-rails ruby


    【解决方案1】:

    无论配方是否已创建,您都将用户重定向到 new 操作。重定向后,new 操作被执行,@recipe = Recipe.new@recipe 设置为不包含任何有关用户之前尝试创建的配方信息的新对象(也没有验证错误)。您应该做的是在创建操作中呈现新操作,而不是重定向。这样的事情可能会有所帮助:

    def create
      @recipe = Recipe.new(recipe_params)
      if @recipe.save
        redirect_to @recipe
      else
        render :new
      end
    end
    

    (我假设您的控制器中有显示操作,并在成功创建后重定向用户以显示操作。如果这不是正确的行为,只需将 redirect_to @recipe 更改为您想要的任何内容)

    【讨论】:

    • 我想你可能得到了渲染和重定向错误的方式,但我切换了它们,现在它正在工作!谢谢
    • 是的,你是对的!感谢您指出这一点。已修复,以免对其他人造成混淆。
    【解决方案2】:

    P。 Boro 得到了它,但我认为他们把 if 和 else 弄错了,我的控制器现在看起来像这样并且它正在工作!

    def create
      @recipe = Recipe.new(recipe_params)
      if @recipe.save
        redirect_to @recipe
      else
        render :new
      end
    end
    

    谢谢

    【讨论】:

      【解决方案3】:

      很高兴听到您找到了解决方案。

      但是您是 Ruby 和 Rails 的新手,所以我想建议您,首先通过 scaffold generator 了解 MVC 的基本概念以及 CRUD 操作在 Rails 中的工作原理?

      用脚手架生成代码后深入探索。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-10-12
        • 2012-11-05
        • 2016-08-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多