I have a model "User" with attribute "Username". Can I use validations to prevent a User being created with the Username "home"?
class User < ActiveRecord::Base
validates :username, presence: true
end
You can use an exclusion validator:
class User < ActiveRecord::Base
USERNAME_BLACKLIST = ['home'].freeze
validates :username, presence: true, exclusion: { in: USERNAME_BLACKLIST }
end
Alternatively, you can always rely on a custom validation method, using validate instead of validates, for more complex types of validation that aren't easily expressed using built-in validators:
class User < ActiveRecord::Base
validates :username, presence: true
validate :username_not_on_restricted_list
protected
def username_not_on_restricted_list
errors.add(:username, :invalid) if username == 'home'
end
end
You could also write a custom validator if you intend to reuse this functionality across multiple models.
Related
I've some Active Record validations on my model:
class Product < ApplicationRecord
validates :name, presence: true, length: { is: 10 }
end
That seems fine. It validates that the field name is not nil, "" and that it must have exactly 10 characters. Now, if I want to add a custom validation, I'd add the validate call:
class Product < ApplicationRecord
validates :name, presence: true, length: { is: 10 }
validate :name_must_start_with_abc
private
def name_must_start_with_abc
unless name.start_with?('abc')
self.errors['name'] << 'must start with "abc"'
end
end
end
The problem is: when the name field is nil, the presence_of validation will catch it, but won't stop it from validating using the custom method, name_must_start_with_abc, raising a NoMethodError, as name is nil.
To overcome that, I'd have to add a nil-check on the name_must_start_with_abc method.
def name_must_start_with_abc
return if name.nil?
unless name.start_with?('abc')
self.errors['name'] << 'must start with "abc"'
end
end
That's what I don't wan't to do, because if I add more "dependant" validations, I'd have to re-validate it on each custom validation method.
How to handle dependant validations on Rails? Is there a way to prevent a custom validation to be called if the other validations haven't passed?
I think there is no perfect solution unless you write all your validations as custom methods. Approach I use often:
class Product < ApplicationRecord
validates :name, presence: true, length: { is: 10 }
validate :name_custom_validator
private
def name_custom_validator
return if errors.include?(:name)
# validation code
end
end
This way you can add as many validations to :name and if any of them fails your custom validator won't execute. But the problem with this code is that your custom validation method must be last.
class Product < ApplicationRecord
validates :name, presence: true, length: { is: 10 }
validate :name_must_start_with_abc, unless: Proc.new { name.nil? }
private
def name_must_start_with_abc
unless name.start_with?('abc')
self.errors['name'] << 'must start with "abc"'
end
end
end
Please check allow_blank, :allow_nil and conditional validation as well for more options.
I'd like to write a validation for preference. It should validate the presence of :city (which is associated with belongs_to) in the case if a preference record for this user exists.
user.rb
# attributes
# :city, :string
has_one :preference
preference.rb
# attributes
# preferred_car_brand
belongs_to :user
I tried this, but records get saved without an error.
user.rb
validates :city, presence: true, if: :user_preference_exists
def user_preference_exists
self.preference.present?
end
You can use this to validate the presence of a field.
class User < ActiveRecord::Base
validates :city, presence: true
end
It won't let active record save user model with empty value for :city.
I'm experimenting in building a roles-based data structure in Rails using Concerns with role-specific methods. I've explored other solutions, like STI, polymorphic associations, but opted to try this method.
All attributes depicted are stored in one table, users.
module Client
extend ActiveSupport::Concern
def self.extended(target)
target.class_eval do
validates :emergency_contact, presence: true
end
end
end
module Doctor
def self.extended(target)
target.class_eval do
validates :credentials, presence: true
end
end
end
class User < ApplicationRecord
validates :role, allow_blank: true, inclusion: { in: roles }
validates :first_name, presence: true
validates :last_name, presence: true
validates :email, presence: true
after_initialize { extend_role }
# Extend self with role-appropriate Concern
def extend_role
extend role.camelize.constantize if role
end
def role=(role)
super(role)
extend_role
end
end
My challenge is during the changing of a role, specifically, what can be done (if anything) to negate the previous role's Concern having extended the User?
Each user will have 1 role, so having the Client and Doctor concerns both mixed into the User would not be appropriate (at this time, at least).
In an ideal solution, the User instance would morph with the role change and retain all changed attributes.
So, calling this:
user.update_attributes({ first_name: 'Wily', last_name: 'McDoc', role: 'doctor' })
...would first handle the role change and then update the attributes.
guess could, in part, remove all methods:
Module.instance_methods.each{|m|
undef_method(m)
}
also, How can I reverse ruby's include function, in case that may be of interest
How can define custom validator that permits first name or last name to be null but not both
My Profile class:
class Profile < ActiveRecord::Base
belongs_to :user
validates :first_name, allow_nil: true
validates :last_name, allow_nil: true
validate :first_xor_last
def first_xor_last
if (first_name.nil? and last_name.nil?)
errors[:base] << ("Specify a first or a last.")
end
end
I tries create by self first_xor_last function but does not work.
I recieve this rspec test:
context "rq11" do
context "Validators:" do
it "does not allow a User without a username" do
expect(User.new(:username=> "")).to_not be_valid
end
it "does not allow a Profile with a null first and last name" do
profile = Profile.new(:first_name=>nil, :last_name=>nil, :gender=>"male")
expect(Profile.new(:first_name=>nil, :last_name=>nil, :gender=>"male")).to_not be_valid
end
it "does not allow a Profile with a gender other than male or female " do
expect(Profile.new(:first_name=>"first", :last_name=>"last", :gender=>"neutral")).to_not be_valid
end
it "does not allow a boy named Sue" do
expect(Profile.new(:first_name=>"Sue", :last_name=>"last", :gender=>"male")).to_not be_valid
end
end
end
I should pass it.
Thanks, Michael.
First of all, allow_nill is not a valid validator. You should be using presence or absence.
Unless you really need a custom message for both fields at the same time, there's no need to use a custom validator, simply do like this:
class Profile < ActiveRecord::Base
belongs_to :user
validates :first_name, :last_name, presence: true
end
If you want to allow either one, you can use conditional validation:
class Profile < ActiveRecord::Base
belongs_to :user
validates :first_name, presence: true, unless: "last_name.present?"
validates :last_name, presence: true, unless: "first_name.present?"
end
Instead of:
errors[:base] << ("Specify a first or a last.")
do
errors.add(:base, "Specify a first or a last.")
EDIT:
The error message you get is not caused by your custom validation, but by two other validations, which seems not needed, just get rid of those two lines:
validates :first_name, allow_nil: true
validates :last_name, allow_nil: true
class Profile < ActiveRecord::Base
belongs_to :user
validate :presence_of_first_or_last_name
def presence_of_first_or_last_name
if (first_name.blank? and last_name.blank?)
errors[:base] << ("Specify a first or a last.")
end
end
end
You can lose the two validates :first_name, allow_nil: true validations since they do absolutely nothing.
Instead of .nil? you might want to use the ActiveSupport method .blank? which checks not just for nil but also if the value is an empty string "" or consists of only whitespaces.
Also as David Newton pointed out XOR is eXclusive OR which would be first_name or last_name but not both. I try to name validators according to the general scheme of ActiveModel::Validations - a descriptive name which tells what kind of validation is performed.
I want to create a model called 'Persona' (which belongs_to model User). The user chooses a name in a form and then clicks the create button, so I need the attribute 'name' in the Persona model. I also want the Persona model to have a lower case version of the persona's name, so I need a second attribute 'downcase_name'. For example, the user may choose the persona's name to be Fooey Barman, so the downcase_name would be fooey barman.
My questions is, how do you initialise the downcase_name attribute? Do you put it in the Persona controller? In the new or create methods? Something like:
def create
#persona = Persona.new(persona_params)
#persona.downcase_name = #persona.name.downcase
if #persona.save
flash[:success] = "Welcome, " + #persona.name
redirect_to #persona
else
render 'new'
end
end
Or do you put it in the model?
class Persona < ActiveRecord::Base
before_create :make_downcase_name
validates :name, presence: true, length: { maximum: 50 }
private
def make_downcase_name
self.downcase_name = name.downcase
end
end
Or perhaps like this?
class Persona < ActiveRecord::Base
validates :name, presence: true, length: { maximum: 50 }
validates :downcase_name, presence: true
end
EDIT:
So, am I right in thinking the way to do it is in the model, with a before_save and a validation, like this?:
class Persona < ActiveRecord::Base
before_save :make_downcase_name
validates :name, presence: true, length: { maximum: 50 }
validates :downcase_name, presence: true
private
def make_downcase_name
self.downcase_name = name.downcase
end
end
The use of the before_* callback seems pretty idiomatic. Alternatively, you can also have a service object created in the controller (say PersonaCreator) that would handle the logic and set the appropriate attributes on the model.
Note that before_create will be called only once, meaning that if the user changes the persona's name later, the callback will not be called. You might want to do something like before_save and check whether the name has been changed.