首页 > 解决方案 > Rails 验证多态关联模型属性

问题描述

在我的 Rails 5.2 应用程序中,我有一个类型为 Car、Bike、Jeep 等的多态模型 Vehicle,它具有 belongs_to 关联车辆类型。我想验证关联的记录属性 display_name。以下代码片段可以完成这项工作,但我想知道一种更好的方法来做到这一点。

class Car < Vehicle
      validates :vehicle_type,
        :inclusion => {
          :in => [VehicleType.find_by(display_name: 'four wheeler')],
          :message => "A Car can only be of vehicle_type 'four wheeler'",
        }
    }

标签: ruby-on-railsactiverecord

解决方案


您应该将验证放在 id 而不是显示名称上,因为如果您决定更改显示名称,则必须重构代码。

class VehiculeType
  FOUR_WHEELER = 1 (id of the four_wheeler type)
end

class Car < Vehicule
  validate :validate_vehicule_type

  private

  def validate_vehicule_type
   errors.add(:vehicule, "A Car can only be of vehicle_type 'four wheeler'") unless vehicule_type_id == VehiculeType::FOUR_WHEELER
  end

end

推荐阅读