amsterdamAL
amsterdamAL

Reputation: 49

render json not showing up in view on rails 4

i have a form set to (remote: true to submit via ajax) where a user can input their email and zipcode. if the record gets validated by the model and saved successfully it triggers a javascript script that changes the dom accordingly to notify the user of success. However, if the record does not pass validation i want to get the errors via json back from the server and display them in a div near the form. However i cant get "else" part of the loop to work and get the json to render on the view.

in the chrome dev tools, when i try to submit a blank form, i get back a status 200 and the response is

{"email":["is invalid"],"zip":["is not a number","is too short (minimum is 5 characters)"]}" 

But how can i get these errors i get back from the controller to show up in the view?

Controller----------------------------------------------->

class EngagesController < ApplicationController

  def now
    @sub = Subscriber.new
  end

  def create
    @sub = Subscriber.new(subscriber_params)

    respond_to do |format|
      if @sub.save
        format.html { render 'now', notice: 'User was successfully created.'     }
        format.js   {}
      else
        format.json { render :json => @sub.errors }
      end
    end
  end      


private
  def subscriber_params
    params.require(:engage).permit(:email, :zip)
  end

end

model---------------------------------------------------->

class Subscriber < ActiveRecord::Base

  validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]    {2,})\z/i
  validates :zip, numericality: {only_integer: true}, length: {minimum: 5}

end

Upvotes: 0

Views: 671

Answers (1)

Vasu Adari
Vasu Adari

Reputation: 908

Instead of rendering json, use

format.js { render 'errors', errors: @subs.errors }

And you need to write view file named errors.js.erb in which you will be displaying errors in the from using JavaScript code.

Upvotes: 1

Related Questions