我有一个简单的评论模型和控制器。当我在我的应用程序中创建注释时,它不会检查我已分配的验证。
这是我的评论模型:
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 %>
<%= link_to 'Cancel', nil, :class => 'cancel' %>
</div>
<% end %>
答案 0 :(得分: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 %>