11

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_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
user456584
  • 86,427
  • 15
  • 75
  • 107
Augusto
  • 1,140
  • 2
  • 18
  • 38

1 Answers1

39

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
felix
  • 11,304
  • 13
  • 69
  • 95
  • Thanks Felix, I added the "private" before the method definition but still I'm getting the same error :( – Augusto Jun 30 '11 at 11:47
  • Oh...could you please post some more code in your model? and yes, like you mentioned in the question, you should also not use params, it should available to you, if it is an attribute in self. – felix Jun 30 '11 at 14:34
  • Hi Felix I updated the question, now the validation code works. Still I'm not sure how to handle the params, as the team_code is not (and shouldn't be) an attribute of the user (that can have many teams after the first one). – Augusto Jun 30 '11 at 14:57
  • http://stackoverflow.com/q/6132642/88898 check this link. It has a answer for your question about passing params. – felix Jun 30 '11 at 15:02
  • 4
    sorry.. what? I don't understand how private and public changes the scope of a method. Is that actually true? – baash05 May 09 '12 at 23:52
  • Why *should* it be private? I understand that it *can* be private. Should everything that can be private be private? – nroose Jun 23 '15 at 17:03
  • 1
    Yes it should. Keep your public interface as small as possible, every programmer that is going to use your code will thank you – 23tux Jun 26 '16 at 08:48