0

我对 Ruby 语言和 Rails 框架有点陌生,但我真的想向注册页面添加一些功能。虽然这段代码有效,但我需要让它更简单、更简洁,但我不知道从哪里开始。

class User < ActiveRecord::Base
  has_many :posts
  has_many :comments
  has_many :votes

  has_secure_password validations: false

  validates :username, presence: true, on: :create, length: {minimum: 5}, uniqueness: true
  validates :username, presence: true, on: :update, length: {minimum: 5}, uniqueness: true

  validates :password, presence: true, on: :create, length: {minimum: 5}
  validates :password, presence: true, on: :update, length: {minimum: 5}

  validates_format_of :username, on: :create, with: /\A[A-Za-z\d_]+\z/, message: "can only include letters and numbers"
  validates_format_of :username, on: :update, with: /\A[A-Za-z\d_]+\z/, message: "can only include letters and numbers"
end

我希望我的用户只能在用户名和密码中包含不带空格的字母和数字。此外,它们都需要至少 5 个字符。现在,只有没有空格的字符和数字适用于我的创建操作,但不适用于我的更新操作。任何帮助将不胜感激。

4

2 回答 2

1

这是一个非常小的模型。

也就是说,有很多改进的空间,因为你已经引入了大量的混乱。

  • 没有理由指定on: :createon: :update进行两次重复验证。如果您只是省略on:,那么它将自动应用于创建更新:

    # Validate on both create AND update
    validates :username, presence: true, length: { minimum: 5 }, uniquess: true 
    
  • 您可以将format验证合并到第一validates行,并将正则表达式大大简化为 just \A\w*\z,因为\w匹配A-Za-z0-9_

    validates :username, presence: true, length: { minimum: 5 }, uniquess: true,
                         format: { with: /\A\w*\z/ }
    
  • 您应该将验证消息移动到config/locals/en.yml而不是直接在模型中。面向用户的字符串在源代码中绝对没有硬编码的位置,它们应该始终驻留在本地化文件中。请参阅i18n 文档

    # config/locals/en.yml
    activerecord:
      errors:
        models:
          user:
            attributes:
              username:
                too_short: "Your username is too short"
                too_long: "Your username is too long"
    

总而言之,您的模型应该如下所示(注意您应该指定最大长度验证以及最小值):

class User < ActiveRecord::Base
  has_many :posts
  has_many :comments
  has_many :votes

  has_secure_password validations: false

  validates :username, presence: true,
                       length: { within: 5..20 },
                       uniqueness: true,
                       format: { with: /\A\w*\z/ }

  validates :password, presence: true,
                       length: { within: 5..20 }
end
于 2013-09-25T02:00:31.600 回答
0
class User < ActiveRecord::Base
  has_many :posts
  has_many :comments
  has_many :votes

  has_secure_password validations: false

  validates :username, presence: true, length: {minimum: 5}, uniqueness: true

  validates :password, presence: true, length: {minimum: 5}

  validates_format_of :username, with: /\A[A-Za-z\d_]+\z/, message: "can only include letters and numbers"
end

如果你做这样的事情

于 2013-09-25T00:05:28.483 回答