How to make a validation rails - ruby-on-rails

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

Related

Ruby on Rails 4. Model conditional validations

I have model with some validation rules:
class Order < ActiveRecord::Base
validates :zip_code, presence: true, length: {is: 5}, numericality: {only_integer: true, :greater_than => 0}
end
And when zip_code is blank i don't need to perform other zip_code validations (it is redundant and all other validation messages on user page look very strange if zip_code is blank)
How can i implement this logic? i need to validate length, is_integer and greater_than only if zip_code is not blank? and i need to show only zip_code can't be blank message on user page
You can do something like
validates :zip_code, presence: true
validates :zip_code, length: {is: 5}, numericality: {only_integer: true, :greater_than => 0}, :if => :zip_code?
Hope it helps!

Ruby on rails Update

I have User model, it has some validations and they work on create. But when i call any user from database as #user=User.find(1) #user.valid? it returns false. Could you help me?
class User < ActiveRecord::Base
validates :name, :surname, :username, :phone, :role, :gender, :presence => true
validates :password_confirmation, :email_confirmation, :presence => true
validates :username, :email, :uniqueness => true
validates :verified, :bulletin, :inclusion => { :in => [true, false] }
validates :password,:email, :confirmation => true
....
end
I guess you need to add on: :create param for each validations that only need to be run on create.
For example when you're doing #user.valid? I gess you don't want to check if password_confirmation is present.
So in this case it should be:
validates :password_confirmation, :email_confirmation, :presence => true, :on => :create
Hope it helps :)
There is a special validation for this use case, that the user should provide a confirmation, but the confirmation is not stored in the database
validates :email, confirmation: true, :uniqueness => true
validates :password, confirmation: true, ....
This substitutes the validation for :password_confirmation and :email_confirmation, so you need also to remove them.
See the fine rails guides http://guides.rubyonrails.org/active_record_validations.html#confirmation

Rails 3 validate presence of many columns with custom messages

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

Rails 3 Validation :presence => false

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 .

Rails validation required numericality even though presence is not set to true

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

Resources