在我的Rails5.2应用程序中,我有一个具有belongs_to关联vehicle_type的汽车、自行车、吉普等类型的多态模型车辆。我想验证关联的记录属性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'",
}
}发布于 2018-05-14 20:36:15
您应该将验证放在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发布于 2018-05-14 22:34:40
我不知道什么是最好的方法,但我会分享我在一个项目中所做的事情:
我决定扩展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
发布于 2019-12-16 01:14:25
我同意Mathieu Larouche的观点。我想在这次讨论中补充的一件小事是,这并不是一个真正的多态关联,因为多态关联是关于“一个模型可以属于一个以上的其他模型,在一个单一的关联上”。这是通过组合使用type和id字段(例如,imageable_id和imageable_type )来完成的。请参见文档here。
这并不会真正影响你的问题的回答,但我只是想提一下,因为多态关联花了我很长的时间来思考,我认为指出区别可能是有帮助的。
https://stackoverflow.com/questions/50323215
复制相似问题