Ruby on rails 验证注释的长度,但不显示错误消息

Ruby on rails 验证注释的长度,但不显示错误消息,ruby-on-rails,ruby,ruby-on-rails-3,Ruby On Rails,Ruby,Ruby On Rails 3,首先,我为我的英语感到抱歉:) 实际上,我正在通过一个简单的应用程序,著名的博客学习Rails 以下是实际的数据库架构: create_table "comments", :force => true do |t| t.integer "post_id" t.text "text" t.datetime "created_at" t.datetime "updated_at" end create_table "posts", :force => true do |t|

首先,我为我的英语感到抱歉:)

实际上,我正在通过一个简单的应用程序,著名的博客学习Rails

以下是实际的数据库架构:

create_table "comments", :force => true do |t|
t.integer  "post_id"
t.text     "text"
t.datetime "created_at"
t.datetime "updated_at"
end

create_table "posts", :force => true do |t|
t.string   "title"
t.text     "text"
t.datetime "created_at"
t.datetime "updated_at"
end
后模型:

class Post < ActiveRecord::Base 
    has_many :comments

    validates_presence_of :title, :message => "title is mandatory"
    validates :text, :length => { :minimum => 10 }
end
class Post“title是必需的”
验证:text,:length=>{:minimum=>10}
结束

当我尝试创建带有文本的帖子时,请尝试以下代码:

def create
   @post = Post.find(params[:post_id])
   @comment = @post.comments.build(params[:comment])
   begin
    @comment.save!
     redirect_to @post
    rescue Exception => error
     puts "Error:: #{error.message}"
     render : new #to not redirect
    end
您的错误将被放到您的控制台上

如果您想在视图中看到此错误,请将其添加到“新建”

<div>
  <% if @comment.errors.any? %>
      <div id="error_explanation">
        <h2>
    <%= pluralize(@comment.errors.count, "error") %> prohibited this comment from being saved:</h2>
        <ul>
          <% @comment.errors.full_messages.each do |msg| %>
              <li><%= msg %></li>
          <% end %>
        </ul>
      </div>
  <% end %>
</div>

禁止保存此评论:

请尝试以下代码:

def create
   @post = Post.find(params[:post_id])
   @comment = @post.comments.build(params[:comment])
   begin
    @comment.save!
     redirect_to @post
    rescue Exception => error
     puts "Error:: #{error.message}"
     render : new #to not redirect
    end
您的错误将被放到您的控制台上

如果您想在视图中看到此错误,请将其添加到“新建”

<div>
  <% if @comment.errors.any? %>
      <div id="error_explanation">
        <h2>
    <%= pluralize(@comment.errors.count, "error") %> prohibited this comment from being saved:</h2>
        <ul>
          <% @comment.errors.full_messages.each do |msg| %>
              <li><%= msg %></li>
          <% end %>
        </ul>
      </div>
  <% end %>
</div>

禁止保存此评论:

您如何知道没有错误消息?你是通过控制台试的吗?我怀疑由于您正在重定向到
@post
,您呈现的
Post#show
action视图可能无法处理关联对象的错误消息。如何处理此内部Post#show的错误消息?如何显示错误消息?eduke如果要处理错误消息,必须使用以下代码段。这应该可以工作。您如何知道没有错误消息?你是通过控制台试的吗?我怀疑由于您正在重定向到
@post
,您呈现的
Post#show
action视图可能无法处理关联对象的错误消息。如何处理此内部Post#show的错误消息?如何显示错误消息?eduke如果要处理错误消息,必须使用以下代码段。这应该可以工作。