带有遥控器的Rails4 Form-处理错误消息

时间:2018-06-22 21:48:51

标签: ruby-on-rails ajax forms ruby-on-rails-4 error-handling

我有一个简单的远程表单,如下所示:

= form_for :question, :url => question_path, :remote => true, :html =>{:class => 'question-form'} do |form|

,然后在我的控制器中检查是否接受EULA形式:

  def create
    if (params[:question][:eula] != 1)
      puts "ERROR!"
      respond_to do |format|
          return format.json {render :json => {:error_message => "FOOOO", :success => false } }
      end
    end
    @question = Question.new(question_params)

    respond_to do |format|
      if @question.save
        format.html { redirect_to @question, notice: 'question was successfully created.' }
        format.json { render :show, status: :created, location: @question }
      else
        format.html { render :new }
        format.json { render json: @question.errors, status: :unprocessable_entity }
      end
    end
  end

如何访问create.js.erb文件中的:error_message:success

1 个答案:

答案 0 :(得分:0)

您可以请求Ajax

将ID添加到表单:id => "question-form"

= form_for :question, :url => question_path, :remote => true, 
                  :html =>{:class => 'question-form', :id => "question-form"} do |form|

以及javascript文件中的任何地方

$("#question-form").on("submit", function(e){
    e.preventDefault();
    var form = $(this);
    var request = $.ajax({
        method: "POST",
        beforeSend: function(xhr) {xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))},
        url: "/questions",
        dataType: "json",
        data: form.serialize()
    })

    request.done(function(res){
        console.log(res.success);
    })

    request.catch(function(jqXHR){
        console.log(jqXHR.responseJSON)
    })

})