views:

732

answers:

1

What's the best way to report errors on form fields not associated with a particular model in Rails? As an example, I have a form for the batch creation of user accounts with random users / passwords. It takes as inputs the quantity of users to make, information about what attributes all users should have, and information about the batch which is stored in a user_batches model associated with the created users.

Ideally there would be some errors_on like way to list errors coming from the quantity field, which is associated with no model, the user information fields, associated with the user records that get created, and the user_batches model with minimal code.

This also applies to search forms and the like, which don't get run through AR validations. Any ideas?

+2  A: 

You can add your own errors manually to your model object like this.

@user_batch.errors.add_to_base("Foo")
jdl
Thanks! But, what would you do a case where there's no specific instance to add it to. Like for a search form with multiple options where due to an invalid query no objects were returned? Or for a report that only shows the result of a complex SQL find returning no object, just raw data?
Andrew Cholakian
One approach would be to keep a simple array of the errors that you want to display, which you'd build up over the course of your controller action. Then convert that to a flash message right before rendering.
jdl
Thanks JDL, that's actually what I was hoping to avoid, but it looks like that's what I'll be going with for now. I like how errors_on is so explicitly tied to a form, while a flash message is more tied to the page.
Andrew Cholakian
Well, you could avoid the generic array with the ActiveRecord::BaseWithoutTable plugin. It's more work to set up, but then you get an object that behaves mostly like a regular ActiveRecord object.http://agilewebdevelopment.com/plugins/activerecord_base_without_table
jdl