Any reason expressions are not supported in validations?

I would like to prevent an update action to be executed when a particular "sub-resource" has an attribute set to a particular value. For example "mark order as complete only if its shipment is complete". So it would be nice to write it like this:
update :mark_complete do
validate expr(shipment.status == :delivered)
change set_attribute(:status, :done)
end
update :mark_complete do
validate expr(shipment.status == :delivered)
change set_attribute(:status, :done)
end
It looks like there's no built-in validation to do something like that. Of course, I can manually handle this in many different ways. But I'm wondering why it's not possible - there's probably a good reason. Something like this is possible in policies though. Would a policy be a good candidate to implement this rule?
4 Replies
Chaz Watkins
Chaz Watkins3mo ago
You can add a filter to the update action so it only updates records with status of delivered Or if you want to leverage policies, you can have a policy for this action to only be allowed for delivered status. Both filters and policies support expressions and should suffice.
ZachDaniel
ZachDaniel3mo ago
Expressions are supported just not w/ that syntax, because you have to determine the errror
arconaut
arconautOP3mo ago
Oh, interesting, thanks Zach, I'll take a look at atomic validations.

Did you find this page helpful?