【发布时间】:2016-01-11 03:53:57
【问题描述】:
您好,我有一个名为 PurchasingGroup 的模型,一个采购组有很多目标。
目标模型有 2 个属性: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
【问题讨论】:
-
这个
@goal你想要验证的东西,将在同一个@purchasing_group = PurchasingGroup.find(params[:purchasing_group_id])??? -
Goal和PurchasingGroup之间有什么关联? -
PurchasingGrouphas_manyGoal,是的,一旦验证,@goal 将在 @purchasing_group 内。
标签: validation ruby-on-rails-4 rails-activerecord