Home Simple calculation not working before save, Rails
Reply: 4

Simple calculation not working before save, Rails

Alex Heil
1#
Alex Heil Published in 2018-02-02 20:06:52Z

I've got a base_price field, a shipping_price field, and a total_price field.

It's a simple base_price plus shipping_price equals total_price. For some reason, I cannot get this simple calculation to work when saving my model.

Here's my code:

item.rb

before_save :total_price_calculator

private

  def total_price_calculator
    self.total_price.to_i = self.base_price.to_i + self.shipping_price.to_i
  end

It's failing to make the calculation and save it in the database and I'm not really getting an error as to why.

fool-dev
2#
fool-dev Reply to 2018-02-07 04:48:29Z

Try to the following

self.total_price it automatically saves integer when assigned to this any value integer, that's why you don't need to call to_i

After modified

before_save :total_price_calculator

private

def total_price_calculator
    self.total_price = base_price.to_i + shipping_price.to_i
end

You don't need to use self on base_price and shipping_price because that is are already have values which given from form.

Or you can use directly looks like below

before_save {self.total_price = self.base_price.to_i + self.shipping_price.to_i}

Hope it helps

dstrants
3#
dstrants Reply to 2018-02-02 20:45:31Z

You are applying a method on an assignment here and I suspect that this might be the issue, try it like this:

def total_price_calculator
  self.total_price = self.base_price + self.shipping_price
end

total_price is going to be an int anyway

goose3228
4#
goose3228 Reply to 2018-02-03 00:44:47Z

Try using another methods like before_update/create/validate, inserting breakpoint too see what happens there, returning false to cancel all following callbacks.

Perhaps this is relatable: Rails: How to use before_save to change a field value based on another field?

thedanotto
5#
thedanotto Reply to 2018-02-03 01:12:05Z

try

def total_price_calculator
  self.total_price.to_i = self.base_price.to_i + self.shipping_price.to_i
  true
end

sometimes if it comes out as nil, that returns false for your validation which will rollback the record and not save.

Or to further debug try...

def total_price_calculator
  puts self.base_price.to_i
  puts self.shipping_price.to_i
  puts self.base_price.to_i + self.shipping_price.to_i
  puts self.total_price.to_i = self.base_price.to_i + self.shipping_price.to_i
  self.total_price.to_i = self.base_price.to_i + self.shipping_price.to_i
  true
end

if the last puts returns false or nil, your save will fail validation and not save.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.32913 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO