我有以下模型:
class Order < ActiveRecord::Base
validates :user, :order_status, :delivery_type, presence: true
belongs_to :user
end
在创建新订单之前,我需要检查params中具有user_id的用户是否存在;我可以获取任何user_id,它可能适用于不存在的用户。是否可以通过模型验证来检查是否存在,或者我必须手动进行?谢谢。
您可以validates_associated
用来验证关联的对象,如下所示:
class Order < ActiveRecord::Base
validates :user, :order_status, :delivery_type, presence: true
belongs_to :user
validates_associated :user
end
请注意,presence
即使添加,也不应删除验证validates_associated :user
。请参阅文档中的以下说明:
注意:如果尚未分配关联,则此验证不会失败。如果要确保关联同时存在并保证有效,则还需要使用validates_presence_of。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句