2014-03-29 33 views
0

試圖添加驗證到我的博客帖子,所以當您嘗試添加小於5個字符的標題時,您會收到一條錯誤消息,但此刻我收到此錯誤消息 -試圖添加驗證,但在帖子中得到NameError#創建

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

可您發佈new.html.erb? – Pavan

回答

5

此行

<% @post.errors.full_messages.each do [msg] %> 

應該是這樣

<% @post.errors.full_messages.each do |msg| %> 
+0

是的,只是注意到!謝謝 – Neil

+0

呵呵,舊的錯字。我來不及回答。 :) –

相關問題