ruby-on-rails - 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'",
}
}
解决方案
您应该将验证放在 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
推荐阅读
- android - 如何在kotlin中制作二级构造函数
- wordpress - 自定义字段上的 WordPress date_query
- json - 不同 Json 结构的 Yew 回调
- java - 可以停止(返回)从超级方法继承的类的执行吗?
- python-3.x - 从 FastAPI 中的后台任务获取返回状态
- json - 什么可以使这段代码实现我在颤动中可视化这个饼图的目标?
- javascript - 在 Javascript 中,我希望代码只返回在 HTML 的不同行上具有相同 ID 的名称
- c# - Oracle 数据访问管理器异常
- flutter - URI 中未指定主机
- zurb-foundation - select2 选项列表在 Foundation 模式中更大程度地隐藏