Recently I wanted to check that my test data was valid. Seems like a
reasonable thing to want to do so I thought I’d share the rake task. Add
this code to a rake file in lib/tasks and run with rake
db:fixtures:validate. It will print out the class, record id and error
messages for any model objects that fail validation.
Enjoy!
-Jonathan.
–
namespace :db do
namespace :fixtures do
desc “Load fixtures into the current environment’s database and
display
invalid objects”
task :validate do
Rake::Task[‘db:fixtures:load’].invoke
Object.subclasses_of(ActiveRecord::Base).each do |klass|
klass.find(:all).reject(&:valid?).each do |record|
puts "#{record.class}: id=#{record.id}"
p record.errors.full_messages
puts
end rescue nil
end
end
Nifty idea. Suggestion: replace your explicit use of the ‘id’ field with
the actual primary key, so it will work with classes that use a
non-default primary key.
You always have the id method as a way of accessing a record’s primary
key, regardless of what its actual column name is:
Oh yeah, I went a bit overboard. I guess I knew :id would always work,
but I blinked at the use of the hardwired “id” as the name of the key in
the output. My brain is still woozy from the conference (at which you
were greatly missed!)
On Mon, Apr 24, 2006 at 09:56:25PM +0200, Josh S. wrote:
Jonathan V. wrote:
puts “#{record.class}: id=#{record.id}”
Nifty idea. Suggestion: replace your explicit use of the ‘id’ field with
the actual primary key, so it will work with classes that use a
non-default primary key.