Ben
Ben

Reputation: 759

render/redirect to new action when validation fails (rails)

I have a form where users can enter an isbn and it will try to lookup book data and save it. When validation fails for the isbn lookup (for example if somebody entered it incorrectly), I would like it to redirect to another form where users can enter data in manually if the isbn lookup fails (but not if other validations like numerical price fail).

Any ideas on how to do this? Thanks for the help!

Upvotes: 0

Views: 4168

Answers (2)

Andrew Vit
Andrew Vit

Reputation: 19249

Trying to understand what you're trying to do: please correct me if my assumption is wrong.

If you can't save the model because the ISBN failed validation and you want to display a form for just the ISBN since the other fields are OK, there's a couple things you can do to hold the other attributes in the meantime:

  • Output them as hidden fields when you render the form
  • Store them in session so you can redirect

If you can't save the model then there doesn't seem to be any reason for redirecting to another action: the user is still trying to complete the create action, except you want to render a different form for just the ISBN.

Here's how I'd do it using session, so you can adapt this for redirecting to another action if you need to:

def create
  book = Book.new( params[:book].reverse_merge(session[:unsaved_book]) )
  if book.save?
    session.delete[:unsaved_book]
    flash[:notice] = 'I love it!'
    redirect_to book
  else
    if book.errors.on[:isbn] && book.errors.length == 1
      session[:unsaved_book] = params[:book]
      flash[:error] = 'Sorry, wrong ISBN number.'
      render 'unknown_isbn'
    else
      flash[:error] = 'Check your inputs.'
      render 'new'
    end
  end
end

Upvotes: 1

Maxem
Maxem

Reputation: 2684

I'd give them the option to re enter the isbn if the lookup failed, as it might just be a typo.

For the redirecting part:

redirect_to invalid_input_path and return unless model.valid?
redirect_to isbn_lookup_failed_path and return unless model.do_isbn_lookup
....

Upvotes: 0

Related Questions