您好我有一个名为PurchasingGroup的模型,一个采购组有很多目标。
目标模型有两个属性:no_of_users
和discount
我需要验证目标是否连续,例如,如果我使用no_of_users = 10
和discount = 15
创建目标,那么我创建的下一个目标必须具有更大的值,否则我必须显示错误给用户,现在我在控制器的create
动作中进行验证,我知道这是一个不好的做法,所以我想知道如何创建这个验证,我无法使用自定义验证来实现它模型水平。
我需要访问采购组,然后检查最后一组目标值是否大于或等于新目标的值:
以下是我在控制器中进行的验证,它可以正常工作,但我想做得对:
def create
respond_to do |format|
@purchasing_group = PurchasingGroup.find params[:purchasing_group_id]
@goal = Goal.new goal_params
@error_messages = ""
if not @purchasing_group.goals.empty?
if @purchasing_group.goals.last.no_of_users >= @goal.no_of_users
@error_messages = "The goals are consecutive! No. Users: must be greater than the previous goal value"
end
if @purchasing_group.goals.last.discount >= @goal.discount
@error_messages = "#{@error_messages}\nThe goals are consecutive! discount: must be greater than the previous goal value"
end
end
#if there are no errors then we save the object
if @error_messages.empty?
if @goal.save
@goal.update_attributes purchasing_group_id: params[:purchasing_group_id]
end
end
#In a js template I handle the errors, that is not relevant for this question.
format.js
end
end
答案 0 :(得分:1)
如果我理解你的话,那么:
validate :count_no_of_users
private
def count_no_of_users
last_goal = PurchasingGroup.find(self.purchasing_group_id).goals.last
error(:count_no_of_user, "Should be more than #{last_goal.no_of_user}") if self.no_of_user < last_goal.no_of_user
end
和discount
您可以在单个或单独的验证中验证它。