创建产品时,尝试验证附件是否属于用户。
validates_presence_of:attachment_id,如果:: attachment?
before_save :validate_attachment_id, if: :attachment?
private
def attachment?
product_type == 1
end
def validate_attachment_id
@attachments = Attachment.find_by(user_id: Product.current_user.id, id: attachment_id)
if @attachments.present?
true
else
errors.add(:attachment_id, 'does not belong to you or does not exist')
false
end
end
属于用户的附件很好的结果,它会按预期保存。当它是一个不属于的附件时,它会返回true和false吗?
附件模型不能有belongs_to :product
,但产品型号确实有has_many :attachments
答案 0 :(得分:1)
before_save
。
您应该使用validate :validate_attachment_id, if: :attachment?
代替。