0

如果传递给它们的值符合某些要求,我有几个方法返回true或false。验证器之外的验证方法

这些验证将从几个不同的控制器调用,也可能调用不同的模型。

我想要做到这一点,而不需要将它们插入对象并在对象上运行验证。这可能吗?

我是否将所有这些“验证方法”分组到一个类中?如果是这样,那能够类去”

+1

好像你都反对他们,但是这似乎正好就是Rails的[自定义Validator对象] (http://www.rails-dev.com/custom-validators-in-ruby-on-rails-4)。他们将被存储在'app/validators'中。 – steel

+0

为什么不希望你使用自定义验证器? –

回答

1

您可以使用助手的,这将是在控制器,模型和视图页面中提供

样品:。

在查看页面调用

SampleHelper.just_checker({user_object}) 

如果想在控制器使用,然后包括它。

include SampleHelper 

佣工/ sample_helper.rb

module SampleHelper 

    class << self 
    def just_checker(user) 
     check_admin(user) 
    end 
    end 

    def check_admin(user) 
    redirect_to root_url unless user.admin 
    end 

    # lets use it in controller with before_action 
    def check_admin_with_current_user 
    redirect_to root_url unless current_user.admin 
    end 
end 

samples_controller.rb

class SamplesController < ApplicationController 
include SampleHelper 
before_action :check_admin_with_current_user, only: :destroy 

    def destroy 
    #... 
    end 
end 
+0

我应该在哪里保存这个模块? –

+0

'app/helpers/sample_helper.rb' – 7urkm3n

+0

我必须将此目录添加到我的自动加载路径,还是默认加载? –