[英]How to add a validation to rails model which depends on another model
找不到輕松完成此任務的最佳方法,我想針對以下問題提出數據庫模型。
有一個交易表,其中有一個關聯的帳戶表。 每個帳戶可以有多個聯系人。 現在,一筆交易需要分配一個主要聯系人,該聯系人必須是關聯帳戶的眾多聯系人中的一個。 如何確保主要聯系人是客戶聯系人之一。
Deal Table
account_id
primary_contact_id
Account Table
name and other params
Contact Table
account_id
phone, email etc.
例如。 我目前使用的課程
class Deal < ActiveRecord::Base
belongs_to :account
belongs_to :contact
end
class Account < ActiveRecord::Base
has_many :contacts
has_many :deals
end
class Contact < ActiveRecord::Base
belongs_to :account
has_many :deals
end
我可以在交易模型或控制器中添加驗證,以確保要添加的聯系人是其帳戶聯系人之一。 但是如何處理以下情況:
class Deal
validate :contact_is_among_the_contacts_in_associated_account
private
def contact_is_among_the_contacts_in_associated_account
errors.add(:contact_id, "Your error message") unless contact.in?(account.contacts)
end
end
可能是您可以使用模型回調,例如:
class Deal < ActiveRecord::Base
belongs_to :account
belongs_to :contact
before_update :nullify_contact_association, :if => lambda{|i| i.account_id_changed?}
private
# Nullify contact_id of the deal if it's account association was changed
def nullify_contact_association
self.contact_id = nil
end
end
class Account < ActiveRecord::Base
has_many :contacts
has_many :deals
before_destroy :nullify_dependencies
private
#Deleting an account associated with a deal should
#make sure that contact_id of that deal table is nullified
def nullify_dependencies
self.deals.update_all(:contact_id => nil) if deal.present?
end
end
class Contact < ActiveRecord::Base
belongs_to :account
has_many :deals
before_destroy :nullify_dependencies
private
#Deleting a contact from an account should make sure
#that corresponding contact_id of the deal table is set to nil
def nullify_dependencies
self.deals.update_all(:contact_id => nil) if account.present?
end
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.