Cannot skip validation in Rails 3?

Andrew picture Andrew · Jan 14, 2011 · Viewed 23.4k times · Source

I'm working on a project in Rails 3 where I need to create an empty record, save it to the database without validation (because it's empty), and then allow the users to edit this record in order to complete it, and validate from then on out.

Now I've run into a pretty basic problem: I can't seem to save a model without validating it under any circumstances.

I've tried the following in the console:

model = Model.new
model.save(false) # Returns RuntimeError: Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id
model.save( :validate => false ) # Returns same error as above

model = Model.create
model.save(false) # Same runtime error
model.save( :validate => false ) # Same runtime error

I then tried changing all the validations in the model to :on => :update. Same error messages on any attempt to save.

So what am I missing here? How can I create an empty record and then let validation occur as the user edits it?

Thanks!

Answer

Leventix picture Leventix · Sep 16, 2011

It is a bad practice to have invalid models saved by normal use cases. Use conditional validations instead:

validates_presence_of :title, :unless => :in_first_stage?

or if you have many:

with_options :unless => :in_first_stage? do
  validates_presence_of :title
  validates_presence_of :author
end

This way nothing stands in way to have nightly integrity tests, which checks all records for validity.

A valid use case for saving without validations would be for testing edge cases, e.g. to test that a database constraint is enforced.