1

是否有可能做到这一点?下面的例子:

class A
  validates_presence_of  :text

class B < A
  # should not validate text
4

3 回答 3

3
class A
  # YES
  validates_presence_of :text, if: proc { |record| record.class === A }
  validates_presence_of :text, if: proc { |record| record.class == A }
  validates_presence_of :text, if: proc { |record| record.instance_of? A }

  # NO
  validates_presence_of :text, if: proc { |record| record.is_a? A }
  validates_presence_of :text, if: proc { |record| record.kind_of? A }
  validates_presence_of :text, if: proc { |record| record.class <= A }
  validates_presence_of :text, if: proc { |record| record.class < A }
end

我更喜欢class ===在这种情况下,因为我发现它更明确,但instance_of?更具可读性......选择你喜欢的。

不要使用Object#is_a?, Object#kind_of?, Module#<=,Module#<因为前三个检查包含的子类或模块,第四个只检查子类。

于 2013-10-09T08:48:26.207 回答
2

我的直觉告诉我这可能不是一个好主意,您可能应该检查一下为什么要这样做,但是...

你可以做类似的事情

validates_presence_of :text, :if => Proc.new{ |obj| obj instanceof A  }

没有测试过

于 2013-10-09T08:45:57.887 回答
1

你可以试试:

class B < A

  validators.find{|v| v.is_a? ActiveModel::Validations::PresenceValidator}.attributes.delete :text

我希望有更好的方法来做到这一点。

于 2013-10-09T08:33:54.653 回答