簡體   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