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

杀马特。学长 韩版系。学妹 提交于 2019-12-12 01:40:21

问题


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


来源:https://stackoverflow.com/questions/6673838/please-help-with-this-beta-code-how-can-i-fix-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!