0

I have a rails remote form_for. For several reasons it is a way better idea to use AJAX to submit the form's contents. If there are errors saving the form I want to be able to render a .js.erb file to the page that updates the error div with a partial that displays all the errors.

If there are no errors I want to be able to just redirect and display a flash message.

Is this possible?

0

1 Answer 1

2

You can try something like this in your controller method:

if @code
   flash[:success] = 'Success message'
   render js: "window.location = '#{path}'"
else
   flash.now[:alert] = @instance.errors.full_messages
   render partial: 'your/partial'
end

Detailed explanation:

  • @code stands for a variable that keeps the code/information about executed model method;
  • @instance stands for a model instance;
  • path stands for a path you want to redirect in case there were no errors;
  • render js: <...> is used instead of redirect_to because you've probably set respond_to :html, :js in your controller, so the only way to do a redirect is to use javascript, otherwise you'll get the full rendered page that you are redirecting as an ajax response.
  • flash.now allows you to access messages (in your case, error messages) in the same request, as using only flash allows it only in the next request.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.