Reputation: 548
I'm looking for a way to validate the updating/creating of an item based on the state in an associated record. Basically I have items that belong to an event. If the event is complete, I don't want the items to be able to be changed or new ones added.
class Event < ActiveRecord::Base
has_many :items
end
class Item < ActiveRecord::Base
belongs_to :event
validates_associated :event
end
The Event class has a boolean complete when it is set to true I want the validation of adding/changing an item to fail. I would also like a message to be displayed, something such as 'The event this item belongs to has already been processed and changes may not be made without unprocessing it'
Any help would be greatly appreciated as always!!!
Mark
Upvotes: 0
Views: 149
Reputation: 634
You can do something like this
validate :event_status
def event_status
errors.add(:complete, 'The event was complete') if self.event.complete
end
Upvotes: 2