如何仅对具有多态关联的一个模型指定验证?

How can I specify validation only for one model with polymorphic association?

我有一个多态模型 command,可以关联到 coveradditional_return。 这些是 command 中的字段:

  create_table "commands", force: :cascade do |t|
    t.date     "placement_date"
    t.date     "estimated_delivery_date"
    t.string   "commandable_type"
    t.integer  "commandable_id"
    ...
  end

问题是:对于 cover 我想验证 estimated_delivery_date 但不是模型 additional_return。如何只为一个模型指定验证?

 class Command < ApplicationRecord
   belongs_to :user, dependent: :destroy
   belongs_to :commandable, polymorphic: true
   validates_presence_of :commandable_type,
                         :commandable_id
 end

你可以这样做:

validates :estimated_delivery_date, presence: true, if: :date_required?

private
def date_required?
  commandable.is_a?(Cover)
end