Ruby-on-rails Rails 自定义验证
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6533546/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Rails custom validation
提问by Augusto
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.
我有一个用户注册表单,其中包含常用字段(姓名、电子邮件、密码等)以及“team_invite_code”字段和“角色”弹出菜单。
Before creating the user - only in case the user role is "child" - I would need to:
在创建用户之前 - 只有在用户角色是“孩子”的情况下 - 我需要:
- check if the team_invite_code is present
- check if there is a team in the teams table that has an equal invite code
- associate the user to the right team
- 检查 team_invite_code 是否存在
- 检查团队表中是否有具有相同邀请码的团队
- 将用户与正确的团队相关联
How can I write a proper validation in Rails 2.3.6?
如何在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>
UPDATE:This validation code works:
更新:此验证代码有效:
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
回答by felix
Your validate method child_and_team_code_existsshould be a private or protected method, otherwise in your case it becomes an instance method
您的验证方法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

