我最近开始使用 Rails,到目前为止一切进展顺利。
我已经在我的 Post 模型中设置了acts_as_commentable,它运行良好。问题是用户能够创建“空白”评论。我在acts_as_commentable 生成的comment.rb 文件中添加了以下验证,以限制评论长度:
validates_length_of :comment, :minimum => 3, :too_short => "must be at
least {{count}} words.", :tokenizer => lambda {|str| str.scan(/\w+/) }
validates_length_of :comment, :maximum => 200, :too_long => "must be
shorter than {{count}} words. Make sure there are no links or
elements.", :tokenizer => lambda {|str| str.scan(/\w+/) }
评论的显示视图形式如下:
<%- form_for [@post, @comment] do |f|-%>
<%= f.error_messages %>
<%= f.text_area :comment, :rows => 3 -%>
<p><%= f.submit -%></p>
<%- end -%>
但是,只有在验证失败时我才会收到以下错误(如果创建了正常长度的评论,则该网站可以正常工作):
Template is missing
Missing template comments/create with {:handlers=>[:erb, :rjs, :builder,
:rhtml, :rxml], :formats=>[:html], :locale=>[:en, :en]} in view paths
"/...", "/.../.rvm/gems/ruby-1.9.2-head/gems/devise-1.2.1/app/views"
知道如何仅呈现常规验证错误吗?提前致谢!
更新
CommentsController 根据要求:
class CommentsController < ApplicationController
before_filter :authenticate_user!
def create
@post = Post.find(params[:post_id])
@comment = @post.comments.new(params[:comment])
@comment.user_id = current_user.id
if @comment.save
redirect_to @post
end
end
def destroy
session[:return_to] ||= request.referer
if current_user.admin?
@comment = Comment.find(params[:id])
else
@comment = current_user.comments.find(params[:id])
end
@comment.destroy
respond_to do |format|
format.html { redirect_to session[:return_to] }
format.xml { head :ok }
end
end
end
开发日志:
Started POST "/posts/1/comments" for 127.0.0.1 at 2011-04-18 15:20:05 -0400
Processing by CommentsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"P5x6xSS6VgxPg58Ubftc4FcUQKZFQbpKOKO9zFeE7cM=", "comment"=>{"comment"=>""}, "commit"=>"Create Comment", "post_id"=>"1"}
User Load (0.7ms) SELECT "users".* FROM "users" WHERE "users"."id" = 1 LIMIT 1
SQL (0.3ms) SELECT name
FROM sqlite_master
WHERE type = 'table' AND NOT name = 'sqlite_sequence'
Post Load (0.4ms) SELECT "posts".* FROM "posts" WHERE "posts"."id" = 1 LIMIT 1
Completed in 154ms
ActionView::MissingTemplate (Missing template comments/create with {:handlers=>[:erb, :rjs, :builder, :rhtml, :rxml], :formats=>[:html], :locale=>[:en, :en]} in view paths "/.../app/views", "/.../vendor/plugins/dynamic_form/app/views", "/.../.rvm/gems/ruby-1.9.2-head/gems/devise-1.2.1/app/views"):
Rendered /.../.rvm/gems/ruby-1.9.2-head/gems/actionpack-3.0.6/lib/action_dispatch/middleware/templates/rescues/missing_template.erb within rescues/layout (0.8ms)