【问题标题】:How to validate non-db attributes on an ActiveRecord model?如何验证 ActiveRecord 模型上的非数据库属性?
【发布时间】:2015-06-23 14:07:21
【问题描述】:

我有以下课程:

class Instance < ActiveRecord::Base
  attr_accessor :resolution
  validates_format_of :resolution, with: /\A\d+x{1}\d+\d/

  def resolution=(res)
    validate!
    (set the resolution etc)
  end

  def resolution
    (get the resolution and return)
  end
end

分辨率属性不存储在数据库中,而是实例的临时属性。

当它调用 validate! 时,无论包含什么规则,验证都会失败。没有它,验证根本不起作用。

如何正确验证?

【问题讨论】:

标签: ruby-on-rails validation activerecord


【解决方案1】:

您可以使用=~ 运算符来匹配字符串与正则表达式,使用它您可以在setter 方法中添加条件

def resolution=(res)
  if res =~ /\A\d+x{1}\d+\d/
    # do something
  else
    # errors.add(...)
  end
end

但是,由于你已经使用了attr_accessor,你不必显式定义getter和setter,attr_accessor的作用只是定义getter和setter方法,你可以改为这样做

class Instance < ActiveRecord::Base
  attr_accessor :resolution
  validates_format_of :resolution, with: /\A\d+x{1}\d+\d/
end

上述解决方案将完美运行!

希望这会有所帮助!

【讨论】:

  • 这太棒了!谢谢!我可以结合这两种方法吗? (即有 attr_accessor 和定义的 setter/getter)
  • 是的,当然,您可以覆盖默认方法!
【解决方案2】:

设置变量后应调用validate! 方法。在给定的示例中,当值仍为 nil 时,您调用 validate!

【讨论】:

  • 非常有用!谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-12-16
  • 2012-11-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多