Rails:在JavaScript中捕获错误消息

Rails:在JavaScript中捕获错误消息,javascript,jquery,ruby-on-rails,ruby,ajax,Javascript,Jquery,Ruby On Rails,Ruby,Ajax,我正在使用ajax创建属于特定主题的帖子,我在帖子索引页面中呈现表单。每个帖子都可以有很多标签,我也在使用Desive认证和CanCanCan授权 我需要捕获post submit的错误消息,并通过这个JavaScript模板Create.js.erb在浏览器中显示它,其中包含自定义错误消息,而不是以post形式显示 代码如下: 岗位控制员 class PostsController < ApplicationController load_and_authorize_resource

我正在使用ajax创建属于特定主题的帖子,我在帖子索引页面中呈现表单。每个帖子都可以有很多标签,我也在使用Desive认证和CanCanCan授权

我需要捕获post submit的错误消息,并通过这个JavaScript模板Create.js.erb在浏览器中显示它,其中包含自定义错误消息,而不是以post形式显示

代码如下:

岗位控制员

class PostsController < ApplicationController
  load_and_authorize_resource
  before_action :set_post, only: [:show, :edit, :update, :destroy, :update_status]
  skip_before_action :verify_authenticity_token

  # GET /posts
  # GET /posts.json
  def index
    if params[:topic_id].present?
          @topic = Topic.find(params[:topic_id])
          @posts = @topic.posts.paginate(page: params[:page], per_page: 10)
      @post = @topic.posts.new
    else
      @posts = Post.eager_load(:topic, :user).paginate(page: params[:page], per_page: 10)
    end
    @tags =Tag.all
    end

  # GET /posts/1
  # GET /posts/1.json
  def show
      @tags = @posts.tags
  end

  def update_status
      current_user.posts<<(@posts)
  end

  # GET /posts/new
  def new
      @topic = Topic.find(params[:topic_id])
    @posts = @topic.posts.new
    @tags =Tag.all
  end

  # GET /posts/1/edit
  def edit
    @tags = @posts.tags
  end

  # POST /posts
  # POST /posts.json
  def create

      @topic = Topic.find(params[:topic_id])
    @posts = @topic.posts.create(post_params)

    respond_to do |format|
      @posts.user_id = current_user.id
      if @posts.save
        format.html { redirect_to topic_posts_path(@topic), notice: 'Post was successfully created.' }
        format.js
        format.json { render :show, status: :created, location: @posts }

      else
        format.html { render :new }
        format.json { render json: @posts.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /posts/1
  # PATCH/PUT /posts/1.json
  def update
      @tags = @posts.tags
    respond_to do |format|

      if params[:rate].to_i>0
        @posts.ratings.create(:star => params[:rate])
        format.html { redirect_to post_path(@posts), notice: 'Rating was successfully updated.' }

      elsif @posts.update(post_params)
        format.html { redirect_to post_path(@posts), notice: 'Post was successfully updated.' }
        format.json { render :show, status: :ok, location: @posts }

      else
        format.html { render :edit }
        format.json { render json: @posts.errors, status: :unprocessable_entity }
      end
    end
  end


  # DELETE /posts/1
  # DELETE /posts/1.json
  def destroy
    @posts.destroy
    respond_to do |format|
      format.html { redirect_to topic_posts_url(@posts.topic_id), notice: 'Post was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_post
     @posts = Post.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def post_params
      params.require(:post).permit(:image, :name, :message, :topic_id, {tag_ids:[]}, :rate, :user_id)
    end

  protected

    def json_request?
      request.format.json?
    end
end
class PostsController
发布表单

<%= form_for [@topic, @post], remote: true 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 |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>


    <div class="field">
      <%= f.label :Image %><br>
      <%= f.file_field :image %>
    </div>
    <div class="field">
    <%= f.label :Name %><br>
    <%= f.text_field :name %>
  </div>
  <div class="field">
    <%= f.label :Message %><br>
    <%= f.text_area :message %>

  </div>

  <% if @tags %>
  <% @tags.each do |tag| %>
    <div>
        <%= check_box_tag "post[tag_ids][]", tag.id, @post.tags.include?(tag) %>
        <%= tag.name %>
    </div>
  <% end %>
  <% end %>
  <br><br>

  <%= link_to 'Create Tag', tags_path %>
    <br><br>
  <%= f.submit %>

<% end %>

禁止保存此帖子:







create.js.erb

$("#post_table").append("<%= j render @posts %>");

alert("Post created")
<p id="notice"><%= notice %></p>

<div id='ajax_loader' style="position: absolute; left: 50%; top: 50%; display: none;">
  <%= image_tag "ajax-loader.gif" %>

</div>

<script>

    $(document).ajaxStop(function(){
      $("#ajax_loader").hide();
    });
    $(document).ajaxStart(function(){
      $("#ajax_loader").show();
    });

</script>

<%= will_paginate %>

<h1>Listing Posts</h1>
<table id = "post_table">
  <thead>
  <tr>
    <th><th>Name</th></th>
    <th><th>Author</th></th>
    <th><th>Message</th></th>
    <th><th>Status</th></th>
    <th colspan="4"></th>
  </tr>
  </thead>
  <tbody>
    <%= render @posts %>
  </tbody>
</table>

<br>


<% if @topic %>
    <%= link_to 'New Post', "#", id: "new_post" %>|
      <section id = "new_post_section">
          <%= render 'form' %>
      </section>
    <%= link_to 'Back to Topics', topic_path(@topic) %>
<% else %>
    <% link_to 'New Post', new_post_path %>
<% end %>

<%= will_paginate %>
$(“#post_表”)。追加(“”);
警报(“创建后”)
index.html.erb

$("#post_table").append("<%= j render @posts %>");

alert("Post created")
<p id="notice"><%= notice %></p>

<div id='ajax_loader' style="position: absolute; left: 50%; top: 50%; display: none;">
  <%= image_tag "ajax-loader.gif" %>

</div>

<script>

    $(document).ajaxStop(function(){
      $("#ajax_loader").hide();
    });
    $(document).ajaxStart(function(){
      $("#ajax_loader").show();
    });

</script>

<%= will_paginate %>

<h1>Listing Posts</h1>
<table id = "post_table">
  <thead>
  <tr>
    <th><th>Name</th></th>
    <th><th>Author</th></th>
    <th><th>Message</th></th>
    <th><th>Status</th></th>
    <th colspan="4"></th>
  </tr>
  </thead>
  <tbody>
    <%= render @posts %>
  </tbody>
</table>

<br>


<% if @topic %>
    <%= link_to 'New Post', "#", id: "new_post" %>|
      <section id = "new_post_section">
          <%= render 'form' %>
      </section>
    <%= link_to 'Back to Topics', topic_path(@topic) %>
<% else %>
    <% link_to 'New Post', new_post_path %>
<% end %>

<%= will_paginate %>

$(文档).ajaxStop(函数(){ $(“#ajax_加载程序”).hide(); }); $(文档).ajaxStart(函数(){ $(“#ajax_loader”).show(); }); 列名职位 名称 作者 消息 地位
|
后期模型

class Post < ActiveRecord::Base
  belongs_to :user
  belongs_to :topic
  has_many :comments
  has_and_belongs_to_many :tags
  has_many :ratings


  validates_presence_of :name, :presence => true
  validates_length_of :name, maximum: 5
  has_attached_file :image
  #validates_attachment_presence :image, :presence => true
  validates_attachment_content_type :image, :content_type => ['image/jpeg', 'image/png']
  validates_attachment_size :image, :in => 0..100.kilobytes
end
class Posttrue
验证的长度为:name,最大值为:5
是否已附加文件:图像
#验证\u附件\u presence:image,:presence=>true
验证附件内容类型:图像,内容类型=>['image/jpeg','image/png']
验证\u附件\u大小:image,:in=>0..100.KB
结束

请帮助我。

posts\u controller.rb
中的
create
操作修改为类似的内容(注意
format.js
已添加到
respond\u to
块的
else
子句中):

然后,在
create.js.erb
中,您可以检查错误并按照自己的意愿进行处理。例如:

<% if @post.errors.any? %>
  alert("ERROR(S): <%= j @post.errors.full_messages.join('; ') %>")
<% else %>
  $("#post_table").append("<%= j render @posts %>");
  alert("Post created");
<% end %>

警报(“错误:”)
$(“#post_表”)。追加(“”);
警报(“创建后”);

您可以在
create.js.erb
中使用
@post.errors.full_message
。这是错误消息的集合。punitce是正确的,除了首先需要修改posts控制器,以便在发生错误时使用
create.js.erb
视图模板进行响应(目前没有)。这是有效的。请问,如何让错误出现在flash通知中?当然,这很简单。您需要在控制器操作中添加一行内容:
flash.now[:error]=@post.errors.full\u如果@post.errors.any?
,则显示消息。然后切换
create.js.erb
中的逻辑以提醒flash注意事项:
alert(“错误”);