Rails 自定义验证 [英] Rails custom validation

查看:41
本文介绍了Rails 自定义验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用户注册表单,其中包含常用字段(姓名、电子邮件、密码等)以及team_invite_code"字段和角色"弹出菜单.

I have a user signup form that has the usual fields (name, email, password, etc...) and also a "team_invite_code" field and a "role" popup menu.

在创建用户之前 - 只有在用户角色是孩子"的情况下 - 我需要:

Before creating the user - only in case the user role is "child" - I would need to:

  • 检查 team_invite_code 是否存在
  • 检查团队表中是否有具有相同邀请码的团队
  • 将用户与合适的团队相关联

如何在 Rails 2.3.6 中编写正确的验证?

How can I write a proper validation in Rails 2.3.6 ?

我尝试了以下方法,但出现错误:

I tried the following, but it is giving me errors:

validate :child_and_team_code_exists

def child_and_team_code_exists
   errors.add(:team_code, t("user_form.team_code_not_present")) unless
   self.is_child? && Team.scoped_by_code("params[:team_code]").exists?
end

>> NameError: undefined local variable or method `child_and_team_code_exists' for #<Class:0x102ca7fa8>

更新:此验证代码有效:

def validate 
   errors.add_to_base(t("user_form.team_code_not_present")) if (self.is_child? && !Team.scoped_by_code("params[:team_code]").exists?)
end

推荐答案

您的验证方法 child_and_team_code_exists 应该是私有或受保护的方法,否则在您的情况下它将成为实例方法

Your validate method child_and_team_code_exists should be a private or protected method, otherwise in your case it becomes an instance method

validate :child_and_team_code_exists


private
def child_and_team_code_exists
   errors.add(:team_code, t("user_form.team_code_not_present")) unless
   self.is_child? && Team.scoped_by_code("params[:team_code]").exists?
end

这篇关于Rails 自定义验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆