Question

I'm having some issue figuring out how to handle success on my entries form using rails 3 ujs ajax.

If there are errors, I have a create.js.erb that will alert(j(@entry.errors.full_messages), and this works. But if there are no errors, the form doesn't redirect (because I'm rendering in a dialog) and I'd like the js to alert("success") and close the dialog. (using fancybox 2).

Can you give me some pointers working with rails 3 ujs and ajax?

Was it helpful?

Solution

An approach is to identify and handle the error at controller level instead of view.

def create
  @entry = something
  if @entry.save
    @notice = "Success message!"
    respond_to :js # render default create.js.erb
  else
    respond_to :js { render 'create_error.js.erb' }
  end
end

// create.js.erb
$("#dialog").close();
alert("<%= @notice %>">;

// create_error.js.erb
alert(j(@entry.errors.full_messages);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top