How can I validate that has_many relations are not changed
I have an fairly typical Order model, that has_many Lines
class Order < ActiveRecord::Base
has_many :lines
validates_associated :lines
Once the order is completed, it should not be possible to change any
attributes, or related lines (though you can change the status to not
completed).
validate do
if completed_at.nil? == false && completed_at_was.nil? == false
errors.add(:base, "You can't change once complete")
end
end
This works fine, but, if you add to, remove, or change the associated
Lines, then this isn't prevented.
In my Line model, I have the following validation:
validate do
if order && order.completed_at.nil? == false
errors.add(:base, "Cannot change once order completed.")
end
end
This successfully stops lines in a completed order being modified, and
prevents a line being added to a completed order.
So I need to also prevent lines being taken out of a completed order. I
tried this in the Line model:
validate do
if order_id_was.nil? == false
if Order.find(order_id_was).completed_at.nil? == false
errors.add(:base, "Cannot change once order completed.")
end
end
end
This works fine to prevent a Line being taken out of an Order when
modifying the Line directly. However when you are editing the Order and
remove a Line, the validation never runs, as it has already been removed
from the Order.
So... in short, how can I validate that the Lines associated with an Order
do not change, and are not added to or removed?
I'm thinking I'm missing something obvious.
No comments:
Post a Comment