我有一个用户注册表单,其中包含常用字段(姓名、电子邮件、密码等),还有一个“team_invite_code”字段和一个“角色”弹出菜单。
在创建用户之前 - 只有在用户角色是“ child ”的情况下 - 我需要:
如何在 中编写正确的验证 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>
更新:
此验证码有效:
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
应该是私有(private)或 protected 方法,否则在您的情况下它将成为实例方法
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
关于ruby-on-rails - Rails 自定义验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6533546/