ruby 我的博客文章“Rails中更好的条件验证”的片段

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ruby 我的博客文章“Rails中更好的条件验证”的片段相关的知识,希望对你有一定的参考价值。

def conditionally_validate(attribute, options=nil)
  unless options.nil? 
    unless options[:if].nil?
      options[:if] = "#{options[:if]} && validated_fields.include?(:#{attribute})"
      validates attribute, options
    else
      validates attribute, options.merge(if: "validated_fields.include?(:#{attribute})")
    end
  else
    validate :"validate_#{attribute}", if: "validated_fields.include?(:#{attribute})"
  end
end
def conditionally_validate(attribute, options=nil)
  unless options.nil? 
    unless options[:if].nil?
      options[:if] = "#{options[:if]} && validated_fields.include?(:#{attribute})"
      validates attribute, options
    else
      validates attribute, options.merge(if: "validated_fields.include?(:#{attribute})")
    end
  end
end
def conditionally_validate(attribute, options=nil)
  unless options.nil? 
    validates attribute, options.merge(if: "validated_fields.include?(:#{attribute})")
  end
end
class User < ActiveRecord::Base
  include ConditionalValidations

  conditionally_validate :name, presence: true
  conditionally_validate :email, format: { with: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/ }, length: { maximum: 100 }
end
#pathway2_controller.rb

def create_user
  user = User.new params[:user]
  user.validated_fields = [ :name ]
  user.save
end
#pathway1_controller.rb

def create_user
  user = User.new params[:user]
  user.validated_fields = [ :name, :email ]
  user.save
end
module ConditionalValidations
  attr_accessor :validated_fields
end

ActiveRecord::Base.extend ConditionalValidations
class User < ActiveRecord::Base
  include ConditionalValidations

  # ... your model code
end
def fields_valid?(fields)
  # are there any existing errors?
  original_errors = self.errors.messages.count

  mock = self.dup                  # duplicate the model in a non-persisted way.
  mock.validated_fields = fields   # ...tell model what fields to validate.
  validity = mock.valid?           # run validations and change @errors.

  # run .valid? to repopulate @errors if need be. Otherwise, clear them. 
  (original_errors > 0) ? self.valid? : self.errors.clear
  return validity
end
user.fields_valid? [ :name, :email, :phone ]   # true or false
user = User.new(name: 'Jeff', email: 'blah')

user.validated_fields = [:name, :email]
user.save     # false

user.validated_fields = [:name]
user.save     # true
class Person < ActiveRecord::Base
  validates :surname, presence: true, if: "name.nil?"
end

以上是关于ruby 我的博客文章“Rails中更好的条件验证”的片段的主要内容,如果未能解决你的问题,请参考以下文章

ruby 我们在GitHub内部使用的测试快照,以帮助编辑我们的博客文章,然后再发送给所有人。有关更多信息,请参阅

ruby 我用来将我的Wordpress博客中的帖子导入到新的Jekyll中的脚本。

免费搭建自己的博客

Ckeditor无法保存textarea值(Ruby on Rails)

ActiveModel :: ForbiddenAttributesError使用旧版本的Ruby? [重复]

Ruby on Rails 实时活动通知