【问题标题】:Rails 4: custom validations with external recordsRails 4:使用外部记录进行自定义验证
【发布时间】:2016-01-11 03:53:57
【问题描述】:

您好,我有一个名为 PurchasingGroup 的模型,一个采购组有很多目标。

目标模型有 2 个属性:no_of_usersdiscount

我需要验证目标是连续的,例如,如果我使用 no_of_users = 10discount = 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]) ???
  • GoalPurchasingGroup 之间有什么关联?
  • PurchasingGroup has_many Goal,是的,一旦验证,@goal 将在 @purchasing_group 内。

标签: validation ruby-on-rails-4 rails-activerecord


【解决方案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 也一样

您可以在单个或单独的验证中对其进行验证。

【讨论】:

  • 大坝!!是的,你是对的,我是个混蛋,我忘了我也可以在自定义验证中查询 PurchasingGroup。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多