2015-11-22 27 views
0

我有一個驗證方法,應驗證用戶是否屬於團隊的一部分。如果它不是團隊的一部分,它應該添加一個錯誤,從而無法保存記錄。Rails 4 - 不被稱爲自定義驗證方法

這是一種模型內部當前的方法:

def assignee_must_be_part_of_team 
    unless assignee_id.blank? 
    team = Team.find(self.team_id) 
    errors.add(:team, 'Equipe não existe') unless team 
    user = team.users.find(self.assignee_id) 
    errors.add(:assignee_id, 'Responsável não faz parte da equipe') unless user 
    end 
end 

而且我這個註冊它在我的模型:

validate :assignee_must_be_part_of_team, on: :save 

然而,這種方法不被甚至被稱爲時我保存了一條新紀錄!我甚至試圖添加一些日誌到它,但沒有任何反應,記錄正在保存。

我在這裏錯過了什麼嗎?

回答

1

使用createupdate作爲值:on選項。

更改此:

validate :assignee_must_be_part_of_team, on: :save 

要:

validate :assignee_must_be_part_of_team, on: :create 

或:

validate :assignee_must_be_part_of_team, on: :update 

如果你希望你的驗證,以兩個createupdate操作運行,那麼你不」根本不需要指定:on選項,因爲這是默認行爲。所以,這應該工作:

validate :assignee_must_be_part_of_team 

請參閱the documentation here欲知更多信息。

+1

確實是這樣!謝謝! =) –

0

您在一次驗證中添加了兩個錯誤。也許你可以拆分此爲獨立的驗證,易於調試:

validates :team_id, presence: :true 
validate :belong_to_team, :assignee_part_of_team 

private 
def belong_to_team 
    errors[:team] << 'Equipe não existe' unless self.team 
end 

def assignee_part_of_team 
    errors[:assignee] << 'Responsável não faz parte da equipe' unless self.team and self.team.users.include?(self.assignee) 
end 

然後你就可以知道這是在這裏造成故障。

+0

感謝您的提示!我也實現了它! –