Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I'm migrating an app from rails 2.3 to rails 3. I'm planning on moving to heroku, so I'm also moving to postgres.

I have a model which has lots of fields - about 30. I want to validate the completion of all of these fields, except 2. In my rails 2 app I had:

validates_presence_of (self.column_names - ["id", "email_not_name"]), :on => :update

This worked, and in fact works in Rails3 as well. The problem comes when I try to run the migrations for the new database - I get the "PGError: ERROR: relation “*table_name*” does not exist" error described here. Not sure why this doesn't occur with SQLite3, but it doesn't really matter.

If I remove the validation, the migrations run fine - the problem is that none of the self.column_names actually exist yet. Similarly, if I change the migration to

validates_presence_of :field1, :field2, :on => :update

the migration will run without problems. Clearly, I could just list all 30 fields, but this strikes me as clumsy and not very maintainable. What I really want is:

validates :all, :except=>:email_not_name, :presence=>true, :on => :update

but unfortunately that doesn't actually exist! Is there a way that I can do this without resorting to this? (either rails2 or rails3 style)

Answer:

Ok, so for anyone who comes across this, here's how to do this. The solution is to create a custom error handler, called with:

validate :check_all_questions_completed, :on => :update

The error handler itself is:

def check_all_questions_completed
 Person.column_names.each do |col|
  if (Person.column_names - ["id", "email_not_name"]).include?(col) && send(col).nil?
   errors.add(col)
  end
 aend
end

If anyone can tidy up my code, please do (the model concerned is Person)

share|improve this question

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.