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.
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
t quite know how I
m 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
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
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