【问题标题】:Rails validate polymorphic associated model attributeRails 验证多态关联模型属性
【发布时间】:2018-10-23 16:40:04
【问题描述】:

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

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-rails activerecord


【解决方案1】:

您应该将验证放在 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

【讨论】:

  • 我觉得这不是个好主意,他的vehicle_type是一个实体,所以你得去数据库里找。
  • 等等,我一定是看错了他的问题。通常多态模型类型是类名而不是模型。相应地更改了我的答案,感谢您的提醒!
【解决方案2】:

我不知道什么是最好的方法,但我会分享我在我的一个项目中所做的:

我决定扩展 ActiveModel::Validator 并为我的多态关联创建自己的验证

在你的情况下

class CarValidator < ActiveModel::Validator 
  def validate_vehicle_type(record)
     # where did you save the veicle type associatuon?
     unless VehicleType.find_by(display_name:  record.veicle_type).exists?
    record.errors.add :veicle_type, "This veicle type does not exist"
  end 
end

然后validates with CarValidator

【讨论】:

    【解决方案3】:

    我同意 Mathieu Larouche 的观点。我要在这个讨论中添加的一件小事是,这并不是真正的多态关联,因为多态关联是关于“一个模型如何在一个关联上属于多个其他模型”。这是通过typeid 字段的组合完成的(例如imageable_idimageable_type)。请参阅文档here

    这并不会真正影响对您的问题的回答,但我只是想提一下,因为多态关联让我永远无法理解,我认为说出区别可能会有所帮助。

    【讨论】:

      猜你喜欢
      • 2012-05-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多