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