views:

17

answers:

1

I have a user sign-up form with a registration code field (:reg_code). I have a list of valid registration codes (in a yml file, but doesn't have to be if that makes things easier). I need to check if the user enters in a valid code in the reg code field. I'm a rails/ruby newbie and have NO CLUE how to load & parse the file to check the reg codes.

My class: (the important parts, anyway)

class Foo < ActiveRecord::Base
  ...more class goodness here...
  before_create :validate_reg_code

  def validate_reg_code
    errors.add(:reg_code, "Sorry, this registration code is invalid.") if reg_code
  end

end

I have no clue after the 'if reg code' portion. Please help!

A: 

Personally, I load the registration codes into the database. Create a registration code model and then:

  def validate_reg_code
    unless RegistrationCode.find_by_code(self.reg_code)
      errors.add(:reg_code, "Sorry, this registration code is invalid.") 
    end
  end

If you would like to parse Yaml, you can do so in rails via the YAML::Load command

YAML::load(File.open("#{RAILS_ROOT}/config/registration_codes.yml"))

This will load the yaml file into a hash. I would need to structure of the yaml file to help you further.

Geoff Lanotte
Great! Works like a charm. Thanks so much.
Matthew Freeman