I have built a Rails app that uses the HTML5 Geolocation API to get a user's current position. I use the coordinates to populate a field in my form. I want to know how to validate this in my model. Here is what my form input looks like:
<%= f.input :start_point, label: false, input_html: { id: 'coordinatesStart' } %>
Coordinates should be i the form 54.678, 45.789 and can take any amount of numbers after the decimal point.
Any ideas how I could do this?
I can't run it now but try:
validates :points, format: { with: /\d{1,}\.\d{1,},\s\d{1,}\.\d{1,}/, message: "please enter co-ordinates in correct format"}
The logic being:
Match at least 1 number, followed by a decimal, followed by 1 or more numbers, followed by a comma, followed by a space, followed by one or more numbers, followed by a a decimal, followed by one or more numbers
The latitude must be a number between -90 and 90 and the longitude between -180 and 180.
So in your model:
GEOCOORDINATES_REGEX = /\A-?(?:90(?:(?:\.0*)?)|(?:[0-9]|[1-8][0-9])(?:(?:\.\d*)?)),\s-?(?:180(?:(?:\.0*)?)|(?:[0-9]|[1-9][0-9]|1[0-7][0-9])(?:(?:\.\d*)?))\z/.freeze
validates :start_point, format: { with: GEOCOORDINATES_REGEX }
First thing should be to separate input validation from model stuff. Use some separate layer, even if it's just a bare class implementing ActiveModel::Validations.
Then, add a stand-alone validator class like:
class GeoPairValidator < ActiveModel::EachValidator
RE = /\A\d+\.\d+, ?\d+\.\d+\z/
def validate_each(record, attribute, value)
# value should be "nn.nnnnnnn, nn.nnnnnnn"
record.errors.add(attribute, :invalid, value: value) if value.to_s !~ RE
# split by comma, convert to float
v1, v2 = value.to_s.split(', ').map(&:to_f)
# check logical bounds
record.errors.add(attribute, :invalid, value: value) if v1.abs > 90
record.errors.add(attribute, :invalid, value: value) if v2.abs > 180
end
end
Finally, use it in your input class:
class YourInput
include ActiveModel::Validations
attr_accessor :start_point
validates :start_point, geo_point: true
end
Also check https://api.rubyonrails.org/classes/ActiveModel/Validations/ClassMethods.html#method-i-validates for more detailed information.
We are working with web development firm to build a site. We have a field where we request that the user input the amount that they would like to invest. We asked for this field to be limited to whole numbers. For example, the user should be able to invest "20" or "20.00" but not "20.50".
The developer is using Ruby ActiveRecord Validate_numericality :only_integer which is restricting the input to "20". If a user inputs and submits the value "20.00" they receive an error telling them that they need to input an integer.
Is there a way to use ActiveRecrod validate_numericality to accept only numbers that are whole numbers, not necessarily only integers? The code is currently:
validates :principal, numericality: {greater_than_or_equal_to:MINIMUM_INVESTMENT_AMOUNT,
less_than_or_equal_to:MAXIMUM_INVESTMENT_AMOUNT,
:only_integer => true}
I am hoping that there is a numericality constraint that will allow 20.00 as a whole number.
you could do this
before_validation {|a| a.principal = principal.to_i}
This will convert it to an integer without modifying the validations but if you want to notify the user that they entered something that is not a whole number then I would remove the :only_integer and create a more flexible validation like
validates :principal, numericality:{greater_than_or_equal_to:MINIMUM_INVESTMENT_AMOUNT, less_than_or_equal_to:MAXIMUM_INVESTMENT_AMOUNT}
validate :principal_is_whole_number
def principal_is_whole_number
errors.add(:principal, "must be a whole number.") unless principal.to_i == principal
end
I have a Price model with 4 different fields:
t.decimal "amount"
t.decimal "amount_per_unit"
t.decimal "unit_quantity"
t.string "unit"
I'm trying to make a custom validation that allows either the amount or amount_per_unit fields (this includes unit quantity and unit) to be filled but not both of them. So to make a word diagram of what I mean.
amount = YES
amount_per_unit + unit + unit_quantity = YES
amount_per_unit (alone or amount.present) = NO
unit_quantity (alone or amount.present) = NO
unit (alone or amount.present) = NO
amount and amount_per_unit + unit + unit_quantity = NO
if you still are confused, just know that its either the amount itself thats filled in or the amount per unit fields that are (1 or 3).
So far I tried this validation in my Price model:
validates :amount, :numericality => true
validates :amount_per_unit, :numericality => true
validates :unit_quantity, :numericality => true
validates :unit, :inclusion => UNITS
validate :must_be_base_cost_or_cost_per_unit
private
def must_be_base_cost_or_cost_per_unit
if self.amount.blank? and self.amount_per_unit.blank? and self.unit.blank? and self.unit_quantity
# one at least must be filled in, add a custom error message
errors.add(:amount, "The product must have a base price or a cost per unit.")
return false
elsif !self.amount.blank? and !self.amount_per_unit.blank? and !self.unit.blank? and !self.unit_quantity
# both can't be filled in, add custom error message
errors.add(:amount, "Cannot have both a base price and a cost per unit.")
return false
else
return true
end
end
This validation doesn't work though as all fields are blank it results to a numericality error and if I fill all of them, it creates the price with all fields filled. What needs to be fixed?
I think your values are coming in as nil, not blank.
Try changing the second condition to:
elsif !self.amount.to_s.blank? and !self.amount_per_unit.to_s.blank? and !self.unit.to_s.blank? and !self.unit_quantity.to_s.blank?
Also, it seems you have a typo on the last condition on both statements (e.g. !self.unit_quantity instead of !self.unit_quantity.to_s.blank?
I hope that helps.
I have a model like this.
class Money
include Mongoid::Document
#interval is how often the compensation is paid
field :salary, :type => Integer # must be saved in cents
field :commission, :type => Integer # must be saved in cents
field :total, :type => Integer # must be saved in cents
end
total is sum of salary and commission. salary and commission both are saved in cents.
But my problem is that when it is edited i need to show it in dollar figure.
For example, if salary in cent is 5000000 then when i press edit i need to see 50000 in the salary textbox.
Some other solutions are also welcomed
If you want to enforce this pattern at the model level then you could override the setters and getters:
class Money
#...
def salary
self.salary / 100
end
def salary=(value)
self.salary * 100
end
end
In this case you'll have the editing/displaying for free, without writing any helpers.
Although, I think the proper way for doing it is at the view level through a helper definition. The model should not be concerned with this.
Look at ActionView::Helpers::NumberHelper. In your case you could write your own helper like this:
def money_to_textbox (money)
money / 100
end
This helper method should be placed in app\helpers and then in a view you can use like this:
<%= money_to_textbox #money %>
I'm working on a very basic shopping cart system.
I have a table items that has a column price of type integer.
I'm having trouble displaying the price value in my views for prices that include both Euros and cents. Am I missing something obvious as far as handling currency in the Rails framework is concerned?
You'll probably want to use a DECIMAL type in your database. In your migration, do something like this:
# precision is the total number of digits
# scale is the number of digits to the right of the decimal point
add_column :items, :price, :decimal, :precision => 8, :scale => 2
In Rails, the :decimal type is returned as BigDecimal, which is great for price calculation.
If you insist on using integers, you will have to manually convert to and from BigDecimals everywhere, which will probably just become a pain.
As pointed out by mcl, to print the price, use:
number_to_currency(price, :unit => "€")
#=> €1,234.01
Here's a fine, simple approach that leverages composed_of (part of ActiveRecord, using the ValueObject pattern) and the Money gem
You'll need
The Money gem (version 4.1.0)
A model, for example Product
An integer column in your model (and database), for example :price
Write this in your product.rb file:
class Product > ActiveRecord::Base
composed_of :price,
:class_name => 'Money',
:mapping => %w(price cents),
:converter => Proc.new { |value| Money.new(value) }
# ...
What you'll get:
Without any extra changes, all of your forms will show dollars and cents, but the internal representation is still just cents. The forms will accept values like "$12,034.95" and convert it for you. There's no need to add extra handlers or attributes to your model, or helpers in your view.
product.price = "$12.00" automatically converts to the Money class
product.price.to_s displays a decimal formatted number ("1234.00")
product.price.format displays a properly formatted string for the currency
If you need to send cents (to a payment gateway that wants pennies), product.price.cents.to_s
Currency conversion for free
Common practice for handling currency is to use decimal type.
Here is a simple example from "Agile Web Development with Rails"
add_column :products, :price, :decimal, :precision => 8, :scale => 2
This will allow you to handle prices from -999,999.99 to 999,999.99
You may also want to include a validation in your items like
def validate
errors.add(:price, "should be at least 0.01") if price.nil? || price < 0.01
end
to sanity-check your values.
Just a little update and a cohesion of all the answers for some aspiring juniors/beginners in RoR development that will surely come here for some explanations.
Working with money
Use :decimal to store money in the DB, as #molf suggested (and what my company uses as a golden standard when working with money).
# precision is the total number of digits
# scale is the number of digits to the right of the decimal point
add_column :items, :price, :decimal, precision: 8, scale: 2
Few points:
:decimal is going to be used as BigDecimal which solves a lot of issues.
precision and scale should be adjusted, depending on what you are representing
If you work with receiving and sending payments, precision: 8 and scale: 2 gives you 999,999.99 as the highest amount, which is fine in 90% of cases.
If you need to represent the value of a property or a rare car, you should use a higher precision.
If you work with coordinates (longitude and latitude), you will surely need a higher scale.
How to generate a migration
To generate the migration with the above content, run in terminal:
bin/rails g migration AddPriceToItems price:decimal{8-2}
or
bin/rails g migration AddPriceToItems 'price:decimal{5,2}'
as explained in this blog post.
Currency formatting
KISS the extra libraries goodbye and use built-in helpers. Use number_to_currency as #molf and #facundofarias suggested.
To play with number_to_currency helper in Rails console, send a call to the ActiveSupport's NumberHelper class in order to access the helper.
For example:
ActiveSupport::NumberHelper.number_to_currency(2_500_000.61, unit: '€', precision: 2, separator: ',', delimiter: '', format: "%n%u")
gives the following output
2500000,61€
Check the other options of number_to_currency helper.
Where to put it
You can put it in an application helper and use it inside views for any amount.
module ApplicationHelper
def format_currency(amount)
number_to_currency(amount, unit: '€', precision: 2, separator: ',', delimiter: '', format: "%n%u")
end
end
Or you can put it in the Item model as an instance method, and call it where you need to format the price (in views or helpers).
class Item < ActiveRecord::Base
def format_price
number_to_currency(price, unit: '€', precision: 2, separator: ',', delimiter: '', format: "%n%u")
end
end
And, an example how I use the number_to_currency inside a contrroler (notice the negative_format option, used to represent refunds)
def refund_information
amount_formatted =
ActionController::Base.helpers.number_to_currency(#refund.amount, negative_format: '(%u%n)')
{
# ...
amount_formatted: amount_formatted,
# ...
}
end
If you are using Postgres (and since we're in 2017 now) you might want to give their :money column type a try.
add_column :products, :price, :money, default: 0
Use money-rails gem. It nicely handles money and currencies in your model and also has a bunch of helpers to format your prices.
Using Virtual Attributes (Link to revised(paid) Railscast) you can store your price_in_cents in an integer column and add a virtual attribute price_in_dollars in your product model as a getter and setter.
# Add a price_in_cents integer column
$ rails g migration add_price_in_cents_to_products price_in_cents:integer
# Use virtual attributes in your Product model
# app/models/product.rb
def price_in_dollars
price_in_cents.to_d/100 if price_in_cents
end
def price_in_dollars=(dollars)
self.price_in_cents = dollars.to_d*100 if dollars.present?
end
Source: RailsCasts #016: Virtual Attributes: Virtual attributes are a clean way to add form fields that do not map directly to the database. Here I show how to handle validations, associations, and more.
Definitely integers.
And even though BigDecimal technically exists 1.5 will still give you a pure Float in Ruby.
If someone is using Sequel the migration would look something like:
add_column :products, :price, "decimal(8,2)"
somehow Sequel ignores :precision and :scale
(Sequel Version: sequel (3.39.0, 3.38.0))
My underlying APIs were all using cents to represent money, and I didn't want to change that. Nor was I working with large amounts of money. So I just put this in a helper method:
sprintf("%03d", amount).insert(-3, ".")
That converts the integer to a string with at least three digits (adding leading zeroes if necessary), then inserts a decimal point before the last two digits, never using a Float. From there you can add whatever currency symbols are appropriate for your use case.
It's definitely quick and dirty, but sometimes that's just fine!
I am using it on this way:
number_to_currency(amount, unit: '€', precision: 2, format: "%u %n")
Of course that the currency symbol, precision, format and so on depends on each currency.
You can pass some options to number_to_currency (a standard Rails 4 view helper):
number_to_currency(12.0, :precision => 2)
# => "$12.00"
As posted by Dylan Markow
Simple code for Ruby & Rails
<%= number_to_currency(1234567890.50) %>
OUT PUT => $1,234,567,890.50