views:

39

answers:

2

Hey,

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!

A: 

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
....
Maxem
yep, right now, that is the ONLY option. I can't get the app to redirect to another form where they can manually enter in the data. Right now, they are returned to the original form with just an isbn and price field.
Ben
+1  A: 

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
Andrew Vit
Thanks for the answer!This helped me out a lot.What I ended up doing was saving the params and redirecting to a new form (to clear the ISBN error) where there are only title and author fields, and doing a merge. In the first form, there is only a box for IBSN, price, and comments. The second form (if ISBN is invalid) has title, author, and edition.This way, if the ISBN is invalid, or entered incorrectly, the users have to enter book data manually.
Ben