Quantcast
Channel: User Schwern - Stack Overflow
Viewing all articles
Browse latest Browse all 581

Answer by Schwern for What is the rails way to update a price field before update in a model object generating a total?

$
0
0
self.price = printf('$%.2f',totprice)

This does not set the price, it prints it. printf is for printing and returns nil so that does self.price = nil. You want sprintf.

If price is a number you probably don't want to add a $ to it. Generally avoid adding formatting to numbers in your database, it makes them harder to work with. In that case, use Numeric#round.

self.price = totprice.round(2)

Notes

  • @a and @b are instance variables on the object which will persist. You probably don't want that, and you risk accidentally overwriting other instance variables such as @price. If you just need a local variable in a method use a and b... tho don't use a and b, use descriptive names. See Read This If You Want to Understand Instance Variables in Ruby.
  • It's generally not necessary to check if cert == true. if cert is sufficient.

Consider using rubocop and rubocop-rails to guide you.


Viewing all articles
Browse latest Browse all 581

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>