我正在使用rails 4.1.6我查看了活动记录验证网站并按照他们的指示,但即使出现错误,HTML中也不会显示任何内容。
但是,当我在rails控制台中执行它时,它可以工作。
post = Post.new #create an empty post to test
post.valid? #false
post.errors.messages #this is successfully generate the error message array
但是,它不会在HTML中显示任何错误消息。实际上“@ post.errors”甚至没有运行
-html中的代码
<%= form_for @post, :method => :post do |f| %>
<%= f.label :title %>
<%= f.text_field :title %>
<%= f.label :url %>
<%= f.text_field :url %>
<%= f.submit "Submit" %>
<% if @errors.any? %>
<ul>
<% @errors.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
<% end %>
<% end %>
-My PostsController
def create
# post = Post.new(title: params[:post][:title], url: params[:post][:url])
post = Post.new(post_params)
if post.save
redirect_to posts_path
else
@errors = post.errors.messages
redirect_to paths_path
end
end
private
def post_params
params.require(:post).permit(:title, :url)
end
- 我的帖子模型
class Post < ActiveRecord::Base
validates :title, :length => {maximum: 140, minimum:1}, :presence => true
validates :title, :length => {maximum: 2083, minimum:1}, :allow_blank => true
end
答案 0 :(得分:0)
感谢您的帮助。得到了老师的一些提示。只需使用flash [:message]就可以了。对不起,大家都有麻烦
- 我的控制器代码
def create
post = Post.new(post_params)
if post.save
redirect_to :back
else
flash[:message] = post.errors.messages
redirect_to :back
end
end
- 我的HTML代码
<%= simple_form_for @post, :method => :post do |f| %>
<%= f.label :title %>
<%= f.text_field :title %>
<%= f.label :url %>
<%= f.text_field :url %>
<%= f.submit "Submit" %>
<%= flash[:message] %>
<% end %>
答案 1 :(得分:0)
当涉及到错误时,我确实喜欢偏见,所以我可以在整个应用程序中保持我的错误一样:
应用/视图/共享/ _errors.html.erb:强>
<% if object.errors.any? %>
<h5>The <%= t("activerecord.models.#{object.class.to_s.downcase}") %> could not be saved due to the following errors:</h5>
<ul>
<% object.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
<% end %>
然后,对于您希望显示错误的视图,只需调用:
<%= render 'shared/errors', object: @your_object %>
希望这有帮助!