开发者

Rails custom validation

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:

  • 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

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_ch开发者_运维知识库ild? && 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


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜