Duplicate flash error messages with multiple validations - ruby-on-rails

I am currently validating my model using this code:
validates :price, :presence => true, :numericality => {:greater_than => 0}
This works fine, except that when I do not enter any value in this field, I get 2 errors - both "Price can't be blank" and "Price is not a number".
I can understand why this happens - clearly it is failing both tests. But i'm wondering if there is a way to ge the validation to stop after one test, since there is no point testing if the number is > 0 if there is no number at all?
Thanks!
Edit: For clarity, I don't want to allow the field to be blank, I just don't want the numericality test to run if it is blank, to avoid 2 error messages for what is really 1 error.

Not sure if it will work, but you can try:
validates :price, :presence => true, :numericality => {:greater_than => 0, :allow_blank => true }

Related

update_attributes validation fails though values are correct

I have in my model
class Account < ActiveRecord::Base
validates_length_of :amount, :in 1..255, :on => update, :if => Proc.new { |a| false if a.id == nil;a.amount.blank? }
validates_length_of :name, :in 1..255, :on => update, :if => Proc.new { |a| false if a.id == nil;a.name.blank? }, :unless => user_has_amount?
end
when I comment out the if condition, it works fine but with them validation fails which is confusing. I know that the validation should only run if the proc returns true or unless returns false
in my controller I have
#account.update_attributes({:name => "king", :amount => "1223"}
the save fails and when I check errors I get
#account.errors.details
{:name =>[{:error=>:too_short, :count=>1}], :amount =>[{:error=>:too_short, :count=>1}]}
Strong Params are not an issue because I have
def self.params
params.require(:account).permit!
end
I have no idea why it fails though the value are present and correct.
Try this the following:
class Account < ActiveRecord::Base
validates :amount, length: { in: 1..255 }, on: :update
validates :name, length: { in: 1..255 }, on: :update
end
Check your strong parameters. Your error tells you that something is wrong before you get to validation: :name =>[{:error=>:too_short, :count=>1}] This is saying that the minimum string count is 1 but that your string is not even that long. Here is the docs on that.
You can try: Account.find(1).update_attributes({:name => "king", :amount => "1223"} to see if #account is not being set properly.
You can also customize the language on your errors to help further:
validates_length_of : name, within: 1..255, too_long: 'pick a shorter name', too_short: 'pick a longer name'
The issue that was happening was for one reason. The code was inheriting from a class that had:
slef.reload
in one of the function that were being called during validations.
so every time we try to update the update failed because once that validation was hit it reloaded the original values from database and ignored new values which if old values are empty is just a head scratcher.
Thanks everyone for the help

How to validate price in input?

I have an input (it's text input) where users can set up the price.
The problem is, that users can sometimes set up the price like this:
9
9.99
9,99
$9.99
What's the best way to validate this input? I am running the app on Heroku (= PostgreSQL database), the data type column is decimal.
Rails 4 complains about using $ and ^, so use:
validates :price, :presence => true,
:format => { :with => /\A(\$)?(\d+)(\.|,)?\d{0,2}?\z/ }
Just trying to save people time ;-)
Try something like below. It matches all you examples.
validates :price, :presence => true,
:format => { :with => /^(\$)?(\d+)(\.|,)?\d{0,2}?$/ }

Ruby ActiveRecord: validate format of an integer field

I'm trying to validate the format of a field in an ActiveRecord. I want this field to either be empty, or contain a sequence of digits only (it is containing an optional port number for a database connection). I'm currently trying this:
validates_format_of :port, with: /\A[0-9]*\Z/, message: 'Only numbers allowed'
but without luck. I've found that adding a required number by using for example {1, 6} sort of works, but makes the field mandatory.
Any advice?
Many thanks in advance,
Joseph.
If you're looking to validate so that only numbers are allowed, then you should be able to use this:
validates :port, :numericality => {:only_integer => true}
You may want to try to validate the numericality of the field, like so:
validates_numericality_of :port, :only_integer => true
:only_integer will ensure that the value entered for :port is an integer.
You can also just add allow_blank: true
You can use this syntax as well
validates numericality: :only_integer

Rails 3 validates numericality throws argument error when blank/nil

This seems like kind of a no-brainer but I want to require a number and make sure it is not greater or less than a predetermined amount:
validates :age_min, presence: true, numericality: {
greater_than: 0, less_than_or_equal_to: :age_max
}
This test works as expected
test 'user should not be valid with age min greater than age max' do
user = FactoryGirl.build(:user, age_min: 30, age_max: 20)
assert !user.valid?
end
However, when I try and test that age_min is required:
test 'user should not be valid without age_min' do
user = FactoryGirl.build(:user, age_min: nil, age_max: 20)
assert !user.valid?
end
I get ArgumentError: comparison of Float with nil failed
It seems strange that Rails doesn't take the nil value into account, or am I missing something? It seems you should be able to get this to work without writing a custom validator, but perhaps I am mistaken.
Since your numericality validation for age_min id dependent on the value for age_max, and not a fixed value, I think you want to split your validation out and guard against nil values with procs
validates :age_min, :age_max, :presence => true
validates :age_min, :numericality => {greater_than: 0, less_than_or_equal_to: :age_max}, :unless => Proc.new {|user| user.age_min.nil? || user.age_max.nil? }

Rails greater_than model validation against model attribute

I've got a Trip model, which among other attributes has a start_odometer and end_odometer value.
In my model, i'd like to validate that the end odometer is larger than the starting odometer.
The end odometer can also be blank because the trip may not have finished yet.
However, I can't figure out how to compare one attribute to another.
In trip.rb:
comparing against the symbol:
validates_numericality_of :end_odometer, :greater_than => :start_odometer, :allow_blank => true
gives me the error:
ArgumentError in TripsController#index
:greater_than must be a number
comparing against the variable:
validates_numericality_of :end_odometer, :greater_than => start_odometer, :allow_blank => true
NameError in TripsController#index
undefined local variable or method `start_odometer' for #
You don't necessarily need a custom validation method for this case. In fact, it's a bit overkill when you can do it with one line. jn80842's suggestion is close, but you must wrap it in a Proc or Lambda for it to work.
validates_numericality_of :end_odometer, :greater_than => Proc.new { |r| r.start_odometer }, :allow_blank => true
You'll probably need to write a custom validation method in your model for this...
validate :odometer_value_order
def odometer_value_order
if self.end_odometer && (self.start_odometer > self.end_odometer)
self.errors.add_to_base("End odometer value must be greater than start odometer value.")
end
end
You can validate against a model attribute if you use a Proc.
In rails4 you would do something like this:
class Trip < ActiveRecord::Base
validates_numericality_of :start_odometer, less_than: ->(trip) { trip.end_odometer }
validates_numericality_of :end_odometer, greater_than: ->(trip) { trip.start_odometer }
end
It's a bit kludgy, but this seems to work:
validates_numericality_of :end_odometer, :greater_than => :start_odometer.to_i, :allow_blank => true

Resources