我的user.rb模型太乱了,我不知道如何简化它

时间:2013-09-25 00:00:02

标签: ruby-on-rails ruby

我对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个字符。现在,只有没有空格的字符和数字才能与我的创建操作一起使用,但它对我的更新操作不起作用。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

这是一个非常小的模型。

尽管如此,还是有很大的改进空间,因为你引入了大量的混乱。

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

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

    A-Za-z0-9_
  • 您应该将验证邮件移至validates :username, presence: true, length: { minimum: 5 }, uniquess: true, format: { with: /\A\w*\z/ } ,而不是直接在模型中使用。面向用户的字符串在源代码中绝对没有硬编码的位置,它们总是驻留在本地化文件中。请参阅i18n docs

    config/locals/en.yml

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

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

答案 1 :(得分: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

如果你做这样的事情