使用文件的自定义验证

发布于 2024-09-07 03:34:09 字数 455 浏览 3 评论 0原文

我有一个带有注册码字段(:reg_code)的用户注册表单。我有一个有效的注册代码列表(在 yml 文件中,但如果这使事情变得更容易,则不必如此)。我需要检查用户是否在注册代码字段中输入了有效的代码。我是 Rails/Ruby 新手,不知道如何加载和加载。解析文件以检查注册代码。

我的班级:(无论如何,重要的部分)

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

我在“if reg code”部分之后没有任何线索。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

隐诗 2024-09-14 03:34:09

就我个人而言,我将注册码加载到数据库中。创建一个注册代码模型,然后:

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

如果您想解析 Yaml,您可以在 Rails 中通过 YAML::Load 命令执行

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

此操作,这会将 yaml 文件加载到哈希中。我需要 yaml 文件的结构来进一步帮助您。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文