So far I understood that you only can raise error messages in the controller. The Sale model is a child of the Order model. So I did this:
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
But that does not work. The main goal is to raise an error message whenever a user tries to submit a value that is bigger than the current_user.maxdiscount
.
Any Ideas? Thanks in advance!
Yes, you can record error messages at Model level.
But as you do it in callback, you have to stop the transaction by returning false
or raise an error manually.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.