0

Lets say I have some validations that I only want to run if my record is in a specific state. This allows a draft record to be saved that is incomplete, and the rest of the content can be filled in later.

validates_presence_of :intro, :codename, :body,
  if: lambda { |o| o.content_state == :review }

Now I want to know if this record's content can be considered complete, which will allow it to be moved to the review state. Validations provide a fantastic framework for applying constraints and requirements to model properties, and I want to leverage that.

So I have to take a draft content record, and then validate it as if it was in the review state, and if it comes up with any errors, the content is not yet complete.

But the only way that I have managed to do this is as follows:

def content_completable?
  old_content_state = content_state
  self.content_state = 'review'
  return valid?
ensure
  self.content_state = old_content_state
end

This feels pretty kludgy to me. It seems to work, however I'm powering these states with an actual sate machine, the docs of which say manually assigned a state name is not a good thing. But I have to because there may not be a transition back.

I don't actually want to change the model at this point, even if it is valid. I only want to know if the model would be valid if it were in a different state?

I was hoping ActiveRecords #valid? method would accept a hash attributes that would override the current values on the model, but it doesn't appear to work this way.

Is there a better way to do what I'm doing?

2 Answers 2

0

You could clone the record, modify the state and call valid? on the cloned record.

0

You can set a virtual attribute and test that first:

attr_accessor :new_content_state

validates_presence_of :intro, :codename, :body,
  if: lambda { |o| (o.new_content_state || o.content_state) == :review }

def content_completable?
  self.new_content_state = 'review'
  return valid?
end

Naturally, you may still need to cleanup after the virtual state, but that depends on how long this model persists. It's also less intrusive since you only use this attribute for a limited purpose.

A completely different approach would be to avoid using AR validators in the first place. They aren't quite designed for this purpose, and although it seems elegant at first glance, the abstraction is leaking through...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.