Ruby on Rails | Ruby on Rails如何在 Rails 表单上应用验证

发布于 01-09 23:53 字数 563 浏览 3 评论 0原文

我正在为我的应用程序添加促销代码选项。我想在表单上应用验证,将用户输入的促销代码与管理仪表板中已有的促销代码相匹配(Activeadmin 用于管理仪表板)。

我尝试了几种选择,但没有任何作用。我尝试过的例子 -

def validate_promo_code
  if promo_code.present? and (!promo_code.match(EngineName::PromoCode.promo_code))
    errors.add :promo_code, "must be a valid promo code"
  end
end
def validate_promo_code
 if promo_code.present? and (promo_code != EngineName::PromoCode.where(promo_code: promo_code))
   errors.add :promo_code, "must be valid promo code"
   return;
 end
end

有谁知道如何实现这一目标?请帮忙!

I am adding the promo code option for my application. I want to apply validation on the form that will match the entered promo code by the user to the promo code that has been already there in the admin dashboard (Activeadmin is used for admin dashboard).

I have tried a few options but nothing works. Examples that I have tried -

def validate_promo_code
  if promo_code.present? and (!promo_code.match(EngineName::PromoCode.promo_code))
    errors.add :promo_code, "must be a valid promo code"
  end
end
def validate_promo_code
 if promo_code.present? and (promo_code != EngineName::PromoCode.where(promo_code: promo_code))
   errors.add :promo_code, "must be valid promo code"
   return;
 end
end

Does anyone has any idea how to achieve this? Please Help!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

话少情深2025-01-16 23:53:22

您必须使用 validate dsl 语句让您的 activerecord 模型了解验证。这有效吗?

validate :ensure_valid_promo_code

def ensure_valid_promo_code
  if promo_code.present? && (!promo_code.match(EngineName::PromoCode.promo_code))
    errors.add :promo_code, "must be a valid promo code"
  end
end

You have to make your activerecord model aware of the validation using the validate dsl statement. Does this work?

validate :ensure_valid_promo_code

def ensure_valid_promo_code
  if promo_code.present? && (!promo_code.match(EngineName::PromoCode.promo_code))
    errors.add :promo_code, "must be a valid promo code"
  end
end
浅笑依然2025-01-16 23:53:22

如果有人仍在寻找解决方案,请尝试这个 -

def validate_promo_code
      existing_code = EngineName::PromoCode.where(promo_code: promo_code)
        if promo_code.present? and !(existing_code.present?)
          errors.add :promo_code, "must be valid promo code"
        end
    end

这个解决方案对我有用。

In case if someone is still looking for the solution, try this one -

def validate_promo_code
      existing_code = EngineName::PromoCode.where(promo_code: promo_code)
        if promo_code.present? and !(existing_code.present?)
          errors.add :promo_code, "must be valid promo code"
        end
    end

This solution works for me.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文