未显示Rails验证错误消息



我已经尝试了多种方法来显示视图中的错误消息,但它没有出现。

<%= form_for @article do |f| %>
<% if @article.errors.any? %>
<div id="error_explanation">
<h2>
<%= pluralize(@article.errors.count, "error") %> prohibited
this article from being saved:
</h2>
<ul>
<% @article.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<p>
<%= f.label :title %><br>
<%= f.text_field :title %>
</p>
<p>
<%= f.label :text %><br>
<%= f.text_area :text %>
</p>
<p>
<%= f.submit %>
</p>
<% end %>

_form.html.erb

<center>
<h1>New article</h1>
<%= render 'form' %>
<%= link_to 'Back', articles_path %>
</center>

new.html.erb

class Article < ActiveRecord::Base
#attr_accessible :title, :text
has_many :comments, dependent: :destroy
validates :title, presence: true
end

article.rb

Rails.application.routes.draw do
root "articles#index"
resources :articles do
resources :comments
end
end

routes.rb

class ArticlesController < ApplicationController
http_basic_authenticate_with name: "deba", password: "12345", except: [:index, :show]
def index
@articles = Article.all
end
def new
@article = Article.new
end
def show
@article = Article.find(params[:id])
end

def create
@article = Article.new(article_params)
if @article.save
redirect_to @article
else
render 'new' #@article.errors, status: :unprocessable_entity
end
end
def edit
@article = Article.find(params[:id])
end
def update
@article = Article.find(params[:id])
if @article.update(article_params)
redirect_to @article
else
render 'edit'
end
end
def destroy
@article = Article.find(params[:id])
@article.destroy
redirect_to articles_path
end
private
def article_params
params.require(:article).permit(:title, :text)
end
end

articles_controller.rb

请帮帮我。我试过了,验证是有效的,因为我可以检查,如果没有标题,它重定向到新的页面,而不保存它,但不出现错误信息。

问题是你的重定向-它导致浏览器发起一个新的请求,然后你失去了所有的数据(包括存储错误的实例变量)。而不是重定向,你应该简单地呈现"new"当文章无效时部分。

你还没有发布你的控制器代码,但这应该给你一个方向

if @article.save
# whatever you wanna do if its valid
else
render "new" # render the view without redirecting
end

尝试编辑你的控制器:

class ArticlesController < ApplicationController
before_action :initialize_article, only: [:new, :create]

...
def new
end
def create
if @article.update(article_params)
redirect_to @article
else
render :new
end
end
....
private
def initialize_article
@article ||= Article.new
end
end

相关内容

最新更新