I have a polymorphic model command
who can be associated to a cover
or to an additional_return
.
Those are the field in 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
The thing is : for cover
I would like to validate the estimated_delivery_date
but not for the model additional_return
. How can I specify a validation only for one model ?
class Command < ApplicationRecord
belongs_to :user, dependent: :destroy
belongs_to :commandable, polymorphic: true
validates_presence_of :commandable_type,
:commandable_id
end
You could do something like this:
validates :estimated_delivery_date, presence: true, if: :date_required?
private
def date_required?
commandable.is_a?(Cover)
end