Rails自定义validation

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

在创建用户之前 – 仅在用户角色是“孩子”的情况下 – 我需要:

  • 检查team_invite_code是否存在
  • 检查团队表中是否有团队具有相同的邀请代码
  • 将用户与正确的团队联系起来

如何在Rails 2.3.6中编写适当的validation?

我尝试了以下内容,但它给了我错误:

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 # 

更新:此validation代码有效:

 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 

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

 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