ActiveRecord - 用警告替换模型验证错误

发布于 2024-09-11 17:46:37 字数 849 浏览 6 评论 0原文

我希望在 Rails 中保存/更新模型时能够用警告替换字段错误。基本上,我只想编写一个围绕验证方法的包装器,该包装器将生成错误,保存模型,并且可能在警告哈希中可用(其工作原理与错误哈希相同):

class Person < ActiveRecord::Base
  # normal validation
  validates_presence_of :name

  # validation with warning
  validates_numericality_of :age, 
                            :only_integer => true, 
                            :warning => true # <-- only warn
end

>>> p = Person.new(:name => 'john', :age => 2.2)
>>> p.save
=> true # <-- able to save to db
>>> p.warnings.map { |field, message| "#{field} - #{message}" }
["age - is not a number"] # <-- have access to warning content

知道如何实现这个吗?我能够添加 :warning =>; false 默认值为 ActiveRecord::Validations::ClassMethods::DEFAULT_VALIDATION_OPTIONS 通过扩展模块,但我正在寻找有关如何实现其余部分的一些见解。谢谢。

I want to be able to replace a field error with a warning when saving/updating a model in rails. Basically I want to just write a wrapper around the validation methods that'll generate the error, save the model and perhaps be available in a warnings hash (which works just like the errors hash):

class Person < ActiveRecord::Base
  # normal validation
  validates_presence_of :name

  # validation with warning
  validates_numericality_of :age, 
                            :only_integer => true, 
                            :warning => true # <-- only warn
end

>>> p = Person.new(:name => 'john', :age => 2.2)
>>> p.save
=> true # <-- able to save to db
>>> p.warnings.map { |field, message| "#{field} - #{message}" }
["age - is not a number"] # <-- have access to warning content

Any idea how I could implement this? I was able to add :warning => false default value to ActiveRecord::Validations::ClassMethods::DEFAULT_VALIDATION_OPTIONS
By extending the module, but I'm looking for some insight on how to implement the rest. Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

等待圉鍢 2024-09-18 17:46:37

validation_scopes gem 使用一些很好的元编程魔法来为您提供验证和 ActiveRecord::Errors 的所有常用功能除 object.errors 之外的上下文中的对象。

例如,您可以说:

validation_scope :warnings do |s|
  s.validates_presence_of :some_attr
end

上面的验证将像往常一样在 object.valid? 上触发,但如果 some_attr 不存在,则不会阻止在 object.save 上保存到数据库。任何关联的 ActiveRecord::Errors 对象都可以在 object.warnings 中找到。

以通常方式指定的没有范围的验证仍将按预期运行,阻止数据库保存并将错误对象分配给 object.errors。

作者在他的博客上简要描述了gem的开发。

The validation_scopes gem uses some nice metaprogramming magic to give you all of the usual functionality of validations and ActiveRecord::Errors objects in contexts other than object.errors.

For example, you can say:

validation_scope :warnings do |s|
  s.validates_presence_of :some_attr
end

The above validation will be triggered as usual on object.valid?, but won't block saves to the database on object.save if some_attr is not present. Any associated ActiveRecord::Errors objects will be found in object.warnings.

Validations specified in the usual manner without a scope will still behave as expected, blocking database saves and assigning error objects to object.errors.

The author has a brief description of the gem's development on his blog.

梦回梦里 2024-09-18 17:46:37

我不知道它是否适合 Rails 3,但这个插件可以满足您的需求:

http://softvalidations。 rubyforge.org/

编辑添加:

为了使用 ActiveModel 更新此功能的基本功能,我提出了以下方案:

#/config/initializer/soft_validate.rb:
module ActiveRecord
  class Base
    def warnings
      @warnings ||= ActiveModel::Errors.new(self)
    end
    def complete?
      warnings.clear
      valid?
      warnings.empty?
    end
  end
end

#/lib/soft_validate_validator.rb
class SoftValidateValidator < ActiveModel::EachValidator
  def validate(record)
    record.warnings.add_on_blank(attributes, options)
  end
end

它添加了一个新的类似 Errors 的对象,名为 warnings > 和一个辅助方法完整?,您可以将其添加到模型中,如下所示:

class FollowupReport < ActiveRecord::Base
  validates :suggestions, :soft_validate => true
end

I don't know if it's ready for Rails 3, but this plugin does what you are looking for:

http://softvalidations.rubyforge.org/

Edited to add:

To update the basic functionality of this with ActiveModel I came up with the following:

#/config/initializer/soft_validate.rb:
module ActiveRecord
  class Base
    def warnings
      @warnings ||= ActiveModel::Errors.new(self)
    end
    def complete?
      warnings.clear
      valid?
      warnings.empty?
    end
  end
end

#/lib/soft_validate_validator.rb
class SoftValidateValidator < ActiveModel::EachValidator
  def validate(record)
    record.warnings.add_on_blank(attributes, options)
  end
end

It adds a new Errors like object called warnings and a helper method complete?, and you can add it to a model like so:

class FollowupReport < ActiveRecord::Base
  validates :suggestions, :soft_validate => true
end
酒绊 2024-09-18 17:46:37

我制作了自己的 gem 来解决 Rails 4.1+ 的问题: https://github.com/s12chung/active_warnings

class BasicModel
  include ActiveWarnings

  attr_accessor :name
  def initialize(name); @name = name; end

  warnings do
    validates :name, absence: true
  end
end

model = BasicModel.new("some_name")
model.safe? # .invalid? equivalent, but for warnings
model.warnings # .errors equivalent

I made my own gem to solve the problem for Rails 4.1+: https://github.com/s12chung/active_warnings

class BasicModel
  include ActiveWarnings

  attr_accessor :name
  def initialize(name); @name = name; end

  warnings do
    validates :name, absence: true
  end
end

model = BasicModel.new("some_name")
model.safe? # .invalid? equivalent, but for warnings
model.warnings # .errors equivalent
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文