如何为其他方法调用的方法实现自定义验证?

时间:2013-12-31 02:39:49

标签: ruby-on-rails ruby validation ruby-on-rails-4 custom-validators

我通过方法SubscriptionUser创建.create_subscription(plan_title)

该方法检查是否可以通过.plan_subscribable?(plan)方法订阅(不是超额订阅计划或存档订阅)。

此方法会返回truefalse,但我希望它返回一条错误消息,如果false可以传递给用户。

我如何以及在何处实施这些验证错误?

class User

  def plan_subscribable?(plan)
    users_subscribed = Subscription.where(plan_id: plan.id).size

    return false unless users_subscribed <= plan.quantity
    return false unless plan.archived == false
    return true
  end

  def create_subscription(plan_title)
    plan = Plan.where(title: plan_title).first

    if plan_subscribable?(plan)
      Subscription.create(...)
    end
  end

end

1 个答案:

答案 0 :(得分:2)

您可以修改plan_subscribable?以返回包含特定错误消息的布尔true 字符串

def plan_subscribable?(plan)
  return 'The number of users cannot be higher than the plan quantity' unless users_subscribed <= plan.quantity
  return 'Archived plans are not subscribable' unless plan.archived == false
  return true
end

然后,评估plan_subscribable?的返回值是否为true。如果不是,则语句​​隐式错误,您可以使用返回的值作为错误消息:

def create_subscription(plan_title)
  plan = Plan.where(title: plan_title).first

  subscribable_or_error = plan_subscribable?(plan)
  if subscribable_or_error === true
    Subscription.create(...)
  else
    error_message = subscribable_or_error
  end
end