尝试在我的博客帖子中添加验证,因此当您尝试添加少于5个字符的标题时,您会收到错误消息,但此刻我收到此错误消息 -
NameError in Posts#create
& undefined local variable or method `msg' for #<#<Class:0x007fce95ca04c0>:0x007fce95b4a300>
new.html.erb
<div class = "container">
<h1> New Post </h1>
<%= form_for :post, url: posts_path do |f| %>
<% if @post.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@post.errors.count, "error") %> prohibited this post from being saved:</h2>
<ul>
<% @post.errors.full_messages.each do [msg] %>
<li><%= msg %></li> <error
<% end %>
</ul>
</div>
<% end %>
<p>
<%= f.label :title %><br>
<%= f.text_field :title %>
</p>
<%= f.label :text %><br>
<%= f.text_area :text %>
<p>
<%= f.submit %>
</p>
<%= link_to 'Back', posts_path %>
</div>
<% end %>
posts_controller.rb
class PostsController < ApplicationController
def index
@posts = Post.all
end
def new
@post = Post.new
end
def create
@post = Post.new(params[:post].permit(:title, :text))
if @post.save
redirect_to @post
else
render 'new'
end
end
def show
@post = Post.find(params[:id])
end
private
# Use callbacks to share common setup or constraints between actions.
def post_params
params.require(:post).permit(:title, :text)
end
end
post.rb
class Post < ActiveRecord::Base
validates :title, presence: true,
length: { minimum: 5 }
end
答案 0 :(得分:5)
这一行
<% @post.errors.full_messages.each do [msg] %>
应该是这样的
<% @post.errors.full_messages.each do |msg| %>