ajax - render json not showing up in view on rails 4 -
i have form set (remote: true submit via ajax) user can input email , zipcode. if record gets validated model , saved triggers javascript script changes dom accordingly notify user of success. however, if record not pass validation want errors via json server , display them in div near form. cant "else" part of loop work , json render on view.
in chrome dev tools, when try submit blank form, status 200 , response
{"email":["is invalid"],"zip":["is not number","is short (minimum 5 characters)"]}"
but how can these errors controller show in view?
controller----------------------------------------------->
class engagescontroller < applicationcontroller def @sub = subscriber.new end def create @sub = subscriber.new(subscriber_params) respond_to |format| if @sub.save format.html { render 'now', notice: 'user 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
instead of rendering json, use
format.js { render 'errors', errors: @subs.errors }
and need write view file named errors.js.erb in displaying errors in using javascript code.
Comments
Post a Comment