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.

Was it helpful?

Solution

  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
    

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top