繁体   English   中英

Ruby on Rails 表单错误未显示

[英]Ruby on Rails form errors not displaying

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

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

配方.rb(模型)

class Recipe < ApplicationRecord
    has_many :ingredients
    has_many :steps

    validates_presence_of :title
end

新的.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 %>

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

任何帮助将非常感激。

无论配方是否已创建,您都在将用户重定向到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更改为您想要的任何内容)

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

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

谢谢

很高兴听到你得到了解决方案。

但是您是 Ruby 和 Rails 的新手,所以我想建议您首先通过脚手架生成器了解 MVC 的基本概念以及 CRUD 操作如何在 rails 中工作?

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM