2016-11-23 89 views
1

我正在努力解决某种问题。我有一个轨道模型(mongoid)。Rails - 装饰器内的验证

class User 
    include Mongoid::Document 
    include ActiveModel::SecurePassword 

    validate :password_presence, 
      :password_confirmation_match, 
      :email_presence, 

    field :email 
    field :password_digest 

def password_presence 
end 

def email_presence 
end 

def password_confirmation_match 
end 
end 

我的目标是调用验证取决于我将使用哪个装饰器。比方说,我有两个修饰:

class PasswordDecorator < Draper::Decorator 
def initialize(user) 
    @user = user 
end 
end 

def RegistraionDecorator < Draper::Decorator 
    def initialize(user) 
    @user = user 
    end 
end 

所以现在当我创建/保存/更新内部RegistraionDecorator我的用户对象,我想执行所有的验证方法。

RegistraionDecorator.new(User.new(attrbiutes)) 

但是当我在PasswordDecorator里面做时,我只想调用password_presence方法。

PasswordDecorator.new(User.first) 

当我移动到验证装饰机也不会的Cuz其不同的阶级比我的模型工作。

我该如何做到这一点?

+0

如果你正在创建一个'User'对象而不在任何装饰器中调用它? –

+0

然后将执行所有验证方法,但是我希望对验证方法有更多的控制。 – mike927

+0

验证应仅在型号中出现。你可以根据你的情况决定根据某些'field'或'attr_accessor'的值来运行哪些验证。 –

回答

1

尝试使用表单对象模式。

下面是一个示例(来自一个真实项目),说明如何使用reform来完成它。

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 

奖励:模型不触发验证和多容易在测试中使用。

+0

真棒,这就是我正在寻找的解决方案。我以前不知道改革。谢谢! – mike927