Reputation: 4173
I have a Model with the column completed
. To set completed
to true, it has to match certain validations to become valid.
Is there some easy way to check out if an object is valid with completed
set to true without actually changing the attribute of an object?
Currently I'm doing this:
def ready_for_completion?
self.completed = true
ready = self.valid?
self.completed = false
ready
end
But I think there is a much nicer way to do this, just haven't found out how.
UPDATE:
I should have been more accurate.
My problem is view specific, I have a button on a object which sets completed
to true
after hitting it and I want that button to be disabled if the object is not ready for completion.
Upvotes: 0
Views: 396
Reputation: 17631
I would not validate
your completed
field. It is your responsibility to set this attribute when you feel that your "object" is completed.
You should take a look at state machine
Upvotes: 3
Reputation: 5588
just you can use valid? for test model is valid or not in controller/view/model as
per below example:
if model.valid?
#your code
end
===============
class Person < ActiveRecord::Base
validates :name, presence: true
end
Person.create(name: "John Doe").valid? # => true
Person.create(name: nil).valid? # => false
Upvotes: 0
Reputation: 44685
The approach is correct, however I would wrap it into a method
def as_completed
old_completed = completed
self.completed = true
result = yield
self.completed = old_completed
result
end
Then
def ready_for_completion?
as_completed { valid? }
end
Upvotes: 0