Validating a existence of a beta code before creating a User
-
29-05-2021 - |
Question
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.
Solution
Add a text field to the form for :beta_code
Add an attr_accessor for that field: attr_accessor :beta_code
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
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
OTHER TIPS
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