Ruby on rails Rails-内部装饰器验证
我在为某种问题挣扎。我有一个rails模型(mongoid) 我的目标是调用验证,这取决于我将使用哪个装饰器。假设我有两个装饰师:Ruby on rails Rails-内部装饰器验证,ruby-on-rails,ruby,mongoid,decorator,Ruby On Rails,Ruby,Mongoid,Decorator,我在为某种问题挣扎。我有一个rails模型(mongoid) 我的目标是调用验证,这取决于我将使用哪个装饰器。假设我有两个装饰师: class PasswordDecorator < Draper::Decorator def initialize(user) @user = user end end def RegistraionDecorator < Draper::Decorator def initialize(user) @user = user
class PasswordDecorator < Draper::Decorator
def initialize(user)
@user = user
end
end
def RegistraionDecorator < Draper::Decorator
def initialize(user)
@user = user
end
end
但当我将在PasswordDecorator中执行此操作时,我想调用例如仅password_presence方法
PasswordDecorator.new(User.first)
当我将验证移到decorator时,它将无法工作,因为它的类与我的模型不同
如何实现这一点?尝试使用表单对象模式 下面是一个例子(来自一个真实的项目),说明了如何使用
类PromocodesController
好处:该模型不会触发验证,并且在测试中使用起来非常方便。如果您在没有在任何装饰器中调用的情况下创建
用户
对象,该怎么办?然后将执行所有验证方法,然而,我希望对验证方法有更多的控制。验证应该只存在于模型中。您可以根据一些字段
s或attr\u访问器
s的值决定要运行哪些验证,以适合您的情况为准。决定使用哪个装饰器的标准是什么?您能给我举个例子吗?太棒了,这是我一直在寻找的解决方案。我以前不知道改革。谢谢
RegistraionDecorator.new(User.new(attrbiutes))
PasswordDecorator.new(User.first)
class PromocodesController < ApplicationController
def new
@form = PromocodeForm.new(Promocode.new)
end
def create
@form = PromocodeForm.new(Promocode.new)
if @form.validate(promo_params)
Promocode.create!(promo_params)
redirect_to promocodes_path
else
render :edit
end
end
private
def promo_params
params.require(:promocode).
permit(:token, :promo_type, :expires_at, :usage_limit, :reusable)
end
end
class PromocodeForm < Reform::Form
model :promocode
property :token
property :promo_type
property :expires_at
property :usage_limit
property :reusable
validates_presence_of :token, :promo_type, :expires_at, :usage_limit, :reusable
validates_uniqueness_of :token
validates :usage_limit, numericality: { greater_or_equal_to: -1 }
validates :promo_type, inclusion: { in: Promocode::TYPES }
end