I'm trying to save a record which doesn't have one field set -- which has a validate numericality in the models. Even though the presence is not required in the validation, it's still throwing an error that the field is not a number.
Validation:
validates :network_id, :numericality => true
Code to that is saving model:
networks.each do |network|
network.url = network.raw_data.link
network.save!
end
Error:
Validation failed: Network is not a number
validates :network_id, :numericality => true, :allow_nil => true
validates :network_id, :numericality => {:allow_blank => true}
You should use allow_blank
validates :network_id, :numericality => true, :allow_blank => true
In Rails 4 (Ruby 2), you can write:
validates :network_id, numericality: { greater_than_or_equal_to: 0, allow_nil: true }
You can also write like this...
validates_numericality_of :network_id, allow_nil: true
Related
I want to add a validation in my model of rails: The local team must be different the visiting team.local_team_id is an integer that represent a team and the same for visiting_team_id.This is my code:
class Match < ActiveRecord::Base
validates :mathdate, :presence => true
validate :mydate_is_date?
validates :stage, :presence => true
validates :stage, numericality: {only_integer: true, greater_than_or_equal_to: 1, less_than_or_equal_to: 6}
validates :state, :presence => true
validates :state, numericality: {only_integer: true, greater_than_or_equal_to: 1, less_than_or_equal_to: 3}
validates :local_team_id, :presence => true
validates :visiting_team_id, :presence => true
validates :stadium_id, :presence => true
def mydate_is_date?
errors.add(:contructiondate, 'must be a valid date') if !mathdate.is_a?(Date)
end
Hope you can help me
Thanks
You can add a validation in Rails like so:
validate :team_ids
def team_ids
# if you want to allow blank / nil values
return if local_team_id.nil? && visiting_team_id.nil?
if local_team_id == visiting_team_id
errors.add(:local_team_id, "can't be equal to visiting_team_id")
errors.add(:visiting_team_id, "can't be equal to local_team_id")
end
end
Is there a way to specify many validations like this more concisely?
validates :col_a, :presence => {:message => 'col_a cannot be blank'}
validates :col_b, :presence => {:message => 'col_b cannot be blank'}
validates :col_c, :presence => {:message => 'col_c cannot be blank'}
I'd settle for a generic message if I had to.
You can give multiple field names to a validator
validates :col_a, :col_b, :col_c, :presence => true
You can specify multiple validators in the same line.
validates :col_a, :col_b, :col_c, :presence => true, :numericality => true
The full error message will contain the field name. You don't need to add the field name prefix. If you want to use a custom message then:
validates :col_a, :col_b, :col_c, :presence => {:message => "empty value found"}
You can use
validates :col_a, presence: true
validates :col_b, presence: true
validates :col_c, presence: true
Use the validates_presence_of helper.
validates_presence_of :col_a
EDIT
You could clean it up a bit with validates_each. There is an example on the api page. http://api.rubyonrails.org/classes/ActiveModel/Validations.html
Hope that helps
Does validates :uniqueness get called every time an object is saved even if a field has not changed? Isn't this a performance issue?
validates :name, :schedule_id, :uniqueness => true
It seems to be the case that it does. So isn't it almost always necessary to make sure a change has taken place before running the validation? As every field being checked for uniqueness requires a database hit.
This would be better:
validates :name, :schedule_id, :uniqueness => true, :if => "name_changed? || schedule_id_changed?"
And this much better, if a bit more verbose:
validates :name, :uniqueness => true, :if => :name_changed?
validates :schedule_id, :uniqueness => true, :if => schedule_id_changed?
Gist here: https://gist.github.com/4017019
try this
validates :name, :uniqueness => true, :if => lambda {self.name_changed? }
I want validate presence of these 2 attributes :shipping_cost and :shipping_cost_anywhere if the attribute :shipping is equal to true. and If
I have this in my model but not working fine for me:
validates_presence_of :shipping_cost, :shipping_cost_anywhere, :allow_blank => "true" if :shipping == "true"
this is my :shipping attribute:
field :shipping, :type => Boolean, :default => "false"
How can I do it?
Thank you!
Edited.
I'm using mongoid and simple_form gems
validates_presence_of :shipping_costs_anywhere, :if => :should_be_filled_in?
def should_be_filled_in?
shipping_costs_anywhere == "value"
end
The method will return true or false when it's called in the statement.
No need to put colon in front of shipping_costs_anywhere.
The fix for me to this question is the next code:
validates :shipping_cost, :shipping_cost_anywhere, :presence => true, :if => :shipping?
Thank you to all for your help but any answer has worked for me. thanks!
Stumbled across this today and thought I'd freshen the answer. As others mentioned, you can put the logic in a function. However, you can also just throw it in a proc.
validates_presence_of :shipping_costs_anywhere, :if => Proc.new { |o|
o.shipping_costs_anywhere == "value"}
http://guides.rubyonrails.org/active_record_validations.html#using-a-symbol-with-if-and-unless
The validates is now preferred over validates_presences_of etc. As hyperjas mentioned you can do this:
validates :shipping_cost,
:shipping_cost_anywhere,
:presence => true, :if => :shipping?
However, that conditionalizes the entire validation for both :shipping_cost and :shipping_cost_anywhere. For better maintainability, I prefer a separate validate declaration for each attribute.
More importantly, you will likely run into situations where you have multiple validations with different conditions (like one for presence and another for length, format or value). You can do that like this:
validates :shipping_cost,
presence: { if: :shipping? },
numericality: { greater_than: 100, if: :heavy? }
You can also let rails evaluate a ruby string.
validates :shipping_cost,
presence: { if: "shipping?" },
numericality: { greater_than: 100, if: "shipping? and heavy?" }
And finally, optionally add separate custom messages:
validates :shipping_cost,
presence: { if: "shipping?", message: 'You forgot the shipping cost.' },
numericality: { greater_than: 100, if: "shipping? and heavy?", message: 'Shipping heavy items is $100 minimum.' }
And so on. Hope that helps.
I can't test it, but I think the syntax is more like:
validates_presence_of :shipping_cost, :shipping_cost_anywhere, :allow_blank => "true", :if => "shipping.nil?"
See:
http://guides.rubyonrails.org/active_record_validations_callbacks.html#conditional-validation
Here is my code working for me.Call method on if condition rather than comparing
validates :prefix, :allow_blank => true, :uniqueness => { :case_sensitive => true } ,:if => :trunk_group_is_originating?
def trunk_group_is_originating?
if self.direction == "originating"
true
else
false
end
end
Hope it helps you.......
Here's what I expected to be a perfectly straightforward question, but I can't find a definitive answer in the Guides or elsewhere.
I have two attributes on an ActiveRecord. I want exactly one to be present and the other to be nil or a blank string.
How do I do the equivalent of :presence => false? I want to make sure the value is nil.
validates :first_attribute, :presence => true, :if => "second_attribute.blank?"
validates :second_attribute, :presence => true, :if => "first_attribute.blank?"
# The two lines below fail because 'false' is an invalid option
validates :first_attribute, :presence => false, :if => "!second_attribute.blank?"
validates :second_attribute, :presence => false, :if => "!first_attribute.blank?"
Or perhaps there's a more elegant way to do this...
I'm running Rails 3.0.9
For allowing an object to be valid if and only if a specific attribute is nil, you can use "inclusion" rather than creating your own method.
validates :name, inclusion: { in: [nil] }
This is for Rails 3. The Rails 4 solution is much more elegant:
validates :name, absence: true
class NoPresenceValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
record.errors[attribute] << (options[:message] || 'must be blank') unless record.send(attribute).blank?
end
end
validates :first_attribute, :presence => true, :if => "second_attribute.blank?"
validates :second_attribute, :presence => true, :if => "first_attribute.blank?"
validates :first_attribute, :no_presence => true, :if => "!second_attribute.blank?"
validates :second_attribute, :no_presence => true, :if => "!first_attribute.blank?"
use custom validation.
validate :validate_method
# validate if which one required other should be blank
def validate_method
errors.add(:field, :blank) if condition
end
It looks like :length => { :is => 0 } works for what I need.
validates :first_attribute, :length => {:is => 0 }, :unless => "second_attribute.blank?"
Try:
validates :first_attribute, :presence => {:if => second_attribute.blank?}
validates :second_attribute, :presence => {:if => (first_attribute.blank? && second_attribute.blank? )}
Hope that help .