Rails自定义验证

Aug*_*sto 11 validation ruby-on-rails

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

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

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

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

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

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>
Run Code Online (Sandbox Code Playgroud)

更新: 此验证代码有效:

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
Run Code Online (Sandbox Code Playgroud)

fel*_*lix 38

您的validate方法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
Run Code Online (Sandbox Code Playgroud)

  • 对不起..什么?我不明白私人和公共如何改变方法的范围.这是真的吗? (4认同)