【问题标题】:How can I specify validation only for one model with polymorphic association?如何仅为具有多态关联的一个模型指定验证?
【发布时间】:2017-03-22 09:10:19
【问题描述】:

我有一个多态模型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: Proc.new { |c| c.commandable_type == 'Cover' } 吗?

标签: ruby-on-rails ruby ruby-on-rails-5 polymorphic-associations


【解决方案1】:

你可以这样做:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-30
    • 1970-01-01
    • 2018-10-23
    • 1970-01-01
    • 1970-01-01
    • 2021-04-28
    • 2020-06-09
    • 1970-01-01
    相关资源
    最近更新 更多