到目前为止,我了解到您只能在控制器中引发错误消息。 Sale模型是Order模型的子项。所以我这样做了:
class SalesController < ApplicationController
def create
...
if @sale.errors.any?
flash[:error] = "#{@order.sale.errors.full_messages.to_sentence}"
end
end
class Sale < ActiveRecord::Base
before_save :discount
def discount=(discount)
if discount.present?
if current_user.maxdiscount >= discount.to_d
discount = discount.gsub(",", ".")
self[:discount] = discount
else
self.errors.add(:discount, "The discount is too high. The product was added without it.")
end
end
end
但这不起作用。主要目标是在用户尝试提交大于current_user.maxdiscount
的值时引发错误消息。
任何想法?提前谢谢!
答案 0 :(得分:0)
是的,您可以在模型级别记录错误消息。
但是当你在回调中这样做时,你必须通过返回false
或手动引发错误来停止交易。
class Sale < ActiveRecord::Base
before_save :discount
def discount=(discount)
if discount.present?
if current_user.maxdiscount >= discount.to_d
discount = discount.gsub(",", ".")
self[:discount] = discount
else
self.errors.add(:discount, "The discount is too high. The product was added without it.")
return false
end
end
end