2011-08-17 220 views
2

我有一個簡單的評論模型和控制器。當我在應用程序中創建註釋時,它不會檢查我分配的驗證。驗證問題

這是我的意見型號:

class Comment < ActiveRecord::Base 
    belongs_to :post 

    validates_presence_of :commenter 
    validates_presence_of :body 
end 

創建控制檯評論時,這裏是我的輸出:

>> comment = Comment.new 
=> #<Comment id: nil, commenter: nil, body: nil, post_id: nil, email: nil, created_at: nil, updated_at: nil> 
>> comment.save 
=> false 
>> comment.errors 
=> #<OrderedHash {:body=>["can't be blank"], :commenter=>["can't be blank"]}> 

一切看起來都很好。 但是,如果我在應用程序內部創建了一個空白註釋,它只是說它已成功創建並且實際上不會創建註釋。

這是它記錄:

Started POST "/posts/19/comments" for 127.0.0.1 at Tue Aug 16 23:10:26 -0400 2011 
Processing by CommentsController#create as HTML 
Parameters: {"comment"=>{"body"=>"", "commenter"=>"", "email"=>""}, "commit"=>"Create Comment", "authenticity_token"=>"V/EinZAi2NNYx7AokikTpQFkNtADNiauW5vcNGdhTug=", "utf8"=>"\342\234\223", "post_id"=>"19"} 
Post Load (0.1ms) SELECT "posts".* FROM "posts" WHERE "posts"."id" = 19 LIMIT 1 
Redirected to http://localhost:3000/posts 
Completed 302 Found in 23ms 

對這個有什麼想法?如果它有任何幫助,我可以添加我的實際表單代碼。

UPDATE 控制器代碼:

class CommentsController < ApplicationController 
    def create 
    @post = Post.find(params[:post_id]) 
    @comment = @post.comments.create(params[:comment]) 
    flash[:notice] = "Your comment has been saved." 
    redirect_to (:back) 
    end 
end 

UPDATE 查看代碼:

<%= form_for([post, post.comments.build]) do |f| %> 
       <div class="field"> 
       <h4><%= f.label :name %></h4> 
       <%= f.text_field :commenter %> 
       </div> 
       <div class="field"> 
       <h4><%= f.label :email_address %></h4> 
       <%= f.text_field :email %> 
       </div> 
       <div class="field"> 
       <h4><%= f.label :body %></h4> 
       <%= f.text_area :body %> 
       </div> 
       <div class="actions"> 
       <%= f.submit %>&nbsp; 
       <%= link_to 'Cancel', nil, :class => 'cancel' %> 
       </div> 
      <% end %> 
+0

添加您的控制器代碼。 –

+0

請提供控制器和視圖代碼..註釋實際上並沒有創建,但應用程序說它創建..這是您的問題?.. – rubyprince

+0

這是正確的rubyprince。 –

回答

2

您必須手動檢查是否有錯誤,並顯示它們。這不會奇蹟般地發生。

你必須改變你的控制器中的操作是這樣的:

class CommentsController < ApplicationController 
    def create 
    @post = Post.find(params[:post_id]) 
    @comment = @post.comments.build(params[:comment]) 

    if @comment.save 
     flash[:notice] = "Your comment has been saved." 
     redirect_to (:back) 
    else 
     render 'new' 
    end 
    end 
end 

您可以顯示在您的視圖中的錯誤是這樣的:

<%= f.error_messages %>