2015-09-26 70 views
0

嘗試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 

對這件事有什麼想法?

回答

0

解決此問題的一種方法是僅將經理分配給Administration

class Administration 
    ... 

    before_save :update_organization_id 

    ... 

    def update_organization_id 
    self.organization_id = self.manager.organization_id 
    end 
end 
+1

您的解決方案適合我!這就是ad-hoc編碼所發生的情況。但是,嘿......這正是擺弄的好處。謝謝 – Berdus

0

它看起來像有更多的問題與您的數據模型:organization_id,然後自動使用before_save回調插入。 請不要忘記single responsibility principle。在您的Administration模型中,您的檢查關係在ManagerOrganization之間。 這通常是個壞主意。

你的經理只有一個組織嗎?如果是這樣,更好的解決方案是隻存儲經理Administration,並在需要時致電administration.manager.organization。並將驗證添加到您的Manager型號:

validates :organization, presence: true 
+0

經理不管理組織,而是管理一個或多個主管部門。 Dimakura指出了我的正確方向。 – Berdus