Validating a existence of a beta code before creating a User

Go To StackoverFlow.com

1

model: User

has_one :beta_invite

before_save :beta_code_must_exist

def beta_code_must_exist
    if beta_invite_id == beta_invite.find_by_name(beta_invite.id)
      user
    else
      nil
    end
end

model: BetaInvite

has_many :users

What I`m trying to do is check for the existence of a beta invite in DB, before allowing the user to be saved.

Since the User will be passing in the BetaInvite name into the field, I would like to check if it matches any existing Codes in the DB.

Hope I didn`t mix things up too much.

Would appreciate any help with this problem.

2012-04-05 00:55
by Big_Bird
Are you doing this check on user creation or at anytime the user record is saved - Tim Santeford 2012-04-05 01:26


1

  1. Add a text field to the form for :beta_code

  2. Add an attr_accessor for that field: attr_accessor :beta_code

  3. Then add the following line to the model (Assumes you only want to do this check on user creation):

    validate :beta_code_must_exist, :on => :create

  4. Change beta_code_must_exist to add an error to the form. Also be sure to properly cast :beta_code into the correct type.

    Warning untested code below

    def beta_code_must_exist
      @invite = BetaInvite.find_by_name(beta_code)
      if @invite.empty?
        errors.add(:beta_code, "is not a valid invite code")
      else
        beta_invite_id = @invite.id
      end
    end
    
2012-04-05 01:09
by Tim Santeford
Thanks for the answer, however I dont quite know how Im suppose to check if the user.betainviteid (from the users form) matches the beta_invite.name (for the BetaInvite - Big_Bird 2012-04-05 01:27
Does BetaInvite have both a name and an Id - Tim Santeford 2012-04-05 01:29
Wait does your user record exist at the time of doing this validation? My assumption in this answer is that this is a user signup page where a user record does not even exist yet therefore no prior beta_invite association - Tim Santeford 2012-04-05 01:36
To answer your first question, yes the BetaInvite does have a name & a ID. The user friendly code name is defined as BetaInvite.name. The betainvitationid is (user model) is there so I can associate them properly. The user record doesn`t exist before entering the Beta Invite - Big_Bird 2012-04-05 17:53
The line if beta_invite_id == beta_invite.find_by_name(beta_invite.id) has multiple problems I think. First if the user does not exist then it cannot 'hasone :betainvite'. Second I think you have a typo beta_invite.find_by_name needs to be BetaInvite.find_by_name. Third that same line assumes both the id and the name are the same - Tim Santeford 2012-04-05 18:00


0

Use :inclusion with the :in option. You can supply :in with any enumerable:

validates :beta_invite, :inclusion => { :in => BetaInvite.all,
:message => "%{value} is not a valid beta invite code" }

Source: Rails Active Record Validation

2012-04-05 01:40
by JamesSwift
Ads