嘗試Ruby on Rails我正在擺弄一個小應用程序。到目前爲止,我喜歡rails的方式。我有一個模型管理它有一個管理器和組織。在自定義Rails4模型驗證中限制查詢
我想確保 - 使用驗證 - 分配給管理員的經理與管理員所屬的組織相關聯。
我有一個工作驗證,但我的直覺感覺說這對查詢很昂貴。
class Administration < ActiveRecord::Base
belongs_to :organisation
belongs_to :manager, :class_name => "User", :foreign_key => 'manager_id'
validates :code, numericality: true
validates :manager_id, :presence => true
validates :organisation_id, :presence => true
validates :code, uniqueness: { scope: :organisation_id, message: 'BB: Code already in use' }
validate :manager_belongs_to_organisation
def manager_belongs_to_organisation
errors.add(:base, 'BB: Manager does not exist') unless Organisation.find(self.organisation_id).users.include?(User.find(self.manager_id))
end
end
對這件事有什麼想法?
您的解決方案適合我!這就是ad-hoc編碼所發生的情況。但是,嘿......這正是擺弄的好處。謝謝 – Berdus