views:

326

answers:

3

Given a model that has validations in the model_name.rb file, how can I access those validations manually? I'd like to cook up my own form validation system that would work alongside the built-in Rails tricks and I want to keep everything as DRY as possible. My main problem is that I need to make server-side validations before any of the form values hit the database (I'm using a multistep form).

Basically I'm wondering if there is a method like

User.validations.each do |v|
    puts v.constraint.to_s + " " + v.message
end

Is there anything similar to this?

Thanks in advance.

+1  A: 

My main problem is that I need to make server-side validations before any of the form values hit the database (I'm using a multistep form).

If your model is not valid according to the validations in its class file, then its data won't get saved to the database (unless you pass false to the save method to suppress validations).

  • You can ask a model if it's valid at any point by invoking its valid?/invalid? methods.
John Topley
My form has roughly 4 steps. No models call the .save method until around the third step. However, I still need to do some basic validations (ie, the user is presented several checkbox items to select. I need to output an error if no boxes are selected, etc.) Will the validations still be invoked without calling save?
See my edit above about the valid?/invalid? methods.
John Topley
A: 

The ActiveRecord object exposes the errors method after valid? is called, which gives you messages about which validations are violated. You could check valid? and then check to see if any of the fields on the part of the form you are on are invalid. you could do something like this for a form with fields field1 and field2.

unless x.valid?
  [:field1,:field2].each do |field|
    yes_there_was_an_error if x.errors[field]
  end
end
BaroqueBobcat
A: 

Your best bet is to use a state machine and store the data in the database between the various steps in the form.

You can do e.g. validates_presence_of :username, :if => proc {|u| u.signup_step >= 2 }, where signup_step is an integer column in the database.

So, even though you say you don't want to store it in the database between the forms, I think you should. If you do this, you can use regular validations and models, without nasty hacks. And honestly, I doubt doing it this way is a problem.

August Lilleaas
very nifty! I think I'll give this a shot...and I already do store in the db with sessions...I guess I should have been more clear--I don't store it in the db as an ActiveRecord object until a certain step.Thanks!