Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot skip validation in Rails 3?

Tags:

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!

like image 365
Andrew Avatar asked Jan 14 '11 18:01

Andrew


Video Answer


2 Answers

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.

like image 122
Leventix Avatar answered Sep 30 '22 18:09

Leventix


*sigh...*

Found the problem... one of my after_validate method calls was adding information and resaving the model, hence the errors I was getting weren't from the console input, they were coming from the after_validate method which was saving again.

Thanks all.

like image 39
Andrew Avatar answered Sep 30 '22 16:09

Andrew