これを行うことは可能ですか?以下の例:
class A
validates_presence_of :text
class B < A
# should not validate text
これを行うことは可能ですか?以下の例:
class A
validates_presence_of :text
class B < A
# should not validate text
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#<
。最初の 3 つは含まれているサブクラスまたはモジュールをチェックし、4 番目はサブクラスのみをチェックします。
私の直感では、それはおそらく良い考えではなく、なぜこのようにしているのかを検討する必要があるでしょうが...
次のようなことができます
validates_presence_of :text, :if => Proc.new{ |obj| obj instanceof A }
それをテストしていない
次のようにsthを試すことができます:
class B < A
validators.find{|v| v.is_a? ActiveModel::Validations::PresenceValidator}.attributes.delete :text
ただし、これを行うためのより良い方法があることを願っています。