Ask A Question

Notifications

You’re not receiving notifications from this thread.

How to raise a warning message from the model

Sascha M. asked in General

Hi there,

In my rails app I have the parent model ORDERS with SALES as a child (as nested routes). So 1 Order has_many Sales and 1 Sale belongs_to Order. In my USER model I have the column "maxdiscount". This is the place where a manager types in a value, like 100 $.

Sales agents can give a discount on a SALE. To check if the entered value from the sales agent is not higher than the threshold defined in the maxdiscount I did this:

def discount=(discount)
 if discount.present?
   if current_user.maxdiscount >= discount.to_d
     discount = discount.gsub(",", ".") #gsub for changing comma-seperated values into dot-seperated.
     self[:discount] = discount
   end
 end
end

The check works as intended, but when the if-clause is true like the sales agent typed in a value higher than his maxdiscount threshold then the discount does not get saved. Which is kind of ok.. What I want to do is to raise a warning with a flash message but this does not work. So far I understood that you can't raise error messages from the model.
This is what I did, but that is not working :/

 def discount=(discount)
  if discount.present?
    if current_user.maxdiscount >= discount.to_d
     discount = discount.gsub(",", ".")
     self[:discount] = discount
    else
      self.errors.add(:base, "The discount is too high. The product was added without it.")
     end
   end
  end

Any suggestions? Thanks in advance!

Reply
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 86,563+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.