gpt4 book ai didi

ruby - 导轨 4 : Validating associated ActiveRecord models when using a Form Object

转载 作者:太空宇宙 更新时间:2023-11-03 16:23:09 26 4
gpt4 key购买 nike

我正在使用基于 ActiveModel 的表单对象来处理应用程序的注册(注册)。 signup 类抽象出帐户用户(帐户的主要用户)的信息。

但是,我发现我在 signup 类中复制了 accountuser 的验证逻辑。在我编写规范(使用 rspec)时,我意识到这种重复可能表明我处理它的方式存在问题。

有没有办法将 signup 类中的验证传递给 accountuser 模型而不复制它?这样验证就保留在那些模型中,我可以在 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

关于ruby - 导轨 4 : Validating associated ActiveRecord models when using a Form Object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30290164/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com