我正在使用基于 ActiveModel 的表单对象来处理应用程序的注册(注册)。 signup
类抽象出帐户
和用户
(帐户的主要用户)的信息。
但是,我发现我在 signup
类中复制了 account
和 user
的验证逻辑。在我编写规范(使用 rspec)时,我意识到这种重复可能表明我处理它的方式存在问题。
有没有办法将 signup
类中的验证传递给 account
和 user
模型而不复制它?这样验证就保留在那些模型中,我可以在 signup
类中引用/调用它。
下面是我的 signup
类,但似乎是重复代码...
class Signup
include ActiveModel::Model
# Scopes
#----------------------------------------------------------------------
# NOOP
# Macros
#----------------------------------------------------------------------
attr_accessor :slug, :email, :password, :password_confirmation
# Associations
#----------------------------------------------------------------------
# NOOP
# Validations
#----------------------------------------------------------------------
validate :verify_unique_email
validate :verify_unique_slug
validates :email, presence: true, format: { with: /@/, message: "is invalid" }
validates :password, presence: true, length: { minimum: 8 }, confirmation: true
validates :password_confirmation, presence: true
validates :slug,
presence: true,
format: { with: /\A[\w-]+\z/, message: "is invalid" },
exclusion: { in: %w[signup signups login] }
# Methods
#----------------------------------------------------------------------
def account
@account ||= Account.new
end
def user
@user ||= account.build_primary_user
end
def save
account.active = true
account.slug = slug
user.email = email
user.password = password
user.password_confirmation = password_confirmation
if valid?
ActiveRecord::Base.transaction do
account.save!
user.save!
end
true
else
false
end
end
def save!
save
end
private
def verify_unique_email
if User.exists?(email: email)
errors.add :email, "is invalid"
end
end
def verify_unique_slug
if Account.exists?(slug: slug)
errors.add :slug, "has already been taken"
end
end
end
这是 account
模型,注意验证的重复:
class Account < ActiveRecord::Base
has_one :primary_user, -> { where(primary: true) }, class_name: User
has_many :users, dependent: :destroy
validates :slug,
uniqueness: true,
presence: true,
format: { with: /\A[\w-]+\z/, message: "is invalid" },
exclusion: { in: %w[signup signups login] }
end
我喜欢你用 form object 做的事. validates_associated :user, :account
可能有帮助,但错误消息可能有点奇怪。相反,我可能会使用 mixins for common validations :
class Account < ActiveRecord::Base
module Validations
extend ActiveSupport::Concern
included do
validates :slug, presence: true
end
end
include Validations
end
class Signup
include ActiveModel::Model
include Account::Validations
extend Forwardable
def_delegators :account, :slug
end
我是一名优秀的程序员,十分优秀!