Please help with this beta code, How can I fix it?

2019-09-15 02:27发布

问题:

Possible Duplicate:
Why doesn't this code produce the desired result?

I have the code:

def check_beta_code
    beta_code_array = ['AAAAAAAAAA', 'BBBBBBBBBB', 'CCCCCCCCCC', 'DDDDDDDDDD', 'EEEEEEEEEE']
    beta_code_array.each do |code|
        if :beta_code != code
            errors.add(:beta_code, "Invalid Beta Code")
        end
    end 
end

The problem with this code is that even if someone inputs a correct password, 4 errors are still generated because the other 4 aren't correct.

回答1:

I'm assuming this code is in a model somewhere. You can try creating a model that holds the beta codes and store some values in the DB. Then it's just a matter of querying the db for the code and seeing if there's a match:

# model
class BetaCode < ActiveRecord::Base
  # assumes a field named 'code'
end

# add some codes (via migration, console, manually, etc)
['AAAAAAAAAA', 'BBBBBBBBBB', 'CCCCCCCCCC', 'DDDDDDDDDD', 'EEEEEEEEEE'].each do |code|
  BetaCode.create(:code => code )
end

# and check for a match when user submits code (controller)
@code = BetaCode.find_by_code(user_code)

if @code.present?
  # user is approved
else
  # sorry, no luck
end

If you want to use your snippet, you can always use the member? method for an array.



回答2:

Looks like you just want to see if the array contains a specific code, so you should use the find_index method. It returns the index of the element you're looking for, or nil when the element can't be found (this is the case that interests us).

def check_beta_code(code)
    beta_code_array = ['AAAAAAAAAA', 'BBBBBBBBBB', 'CCCCCCCCCC', 'DDDDDDDDDD', 'EEEEEEEEEE']
    return beta_code_array.find_index(code) != nil
end

check_beta_code 'foobar' # false
check_beta_code 'AAAAAAAAAA' # true