What is the best way, to check that a model relationship is in use in another model to prevent it from being destroyed thus creating an orphan.
Example: I have a Ticket and TicketStatus models. TicketStatus belongs to Ticket. Ticket has_many TicketStatuses.
I should not be able to delete a TicketStatus if it is already assigned to a Ticket. I would like an error message as well.
Easiest ways a callback:
class TicketStatus < ActiveRecord::Base
belongs_to :ticket
before_destroy :check_ticket
private
def check_ticket
if ticket != nil
errors.add_to_base("cannot delete ticket status that has a ticket")
return false
end
end
end
This prevents it and gives you an error.
Hope this helps!
使用before_destroy
回调 ,并确保return false
,这将取消即将发生的删除。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.