Rails Custom Validation
You Must Select One
ActiveRecord comes out of the box with a number of helpful validations. However, there will be situations where you need to create your own custom validation for your model. In this example blog I will walk through an example of how to create a custom validation. This validation will require that at least one toppings is selected for creating a Pizza.
I will first start with a failing test.
it "raises an error if at least one topic is not selected" do
@pizza = FactoryGirl.build(:pizza_without_attribute_selected)
expect(@user.errors.full_messages).to include("Please select at least one topping")
The test above will build out an instance of a pizza where the a topping was not selected. Upon saving the instance of the pizza, I should expect an error with a message “Please select at least one topping”.
My pizza table is setup so that each topping is a boolean data type.
create_table "pizza" do |t|
t.boolean "mozzarella", default: false, null: false
t.boolean "basil", default: false, null: false
t.boolean "mushrooms", default: false, null: false
In my Pizza class, I create a validation :must_select_one_topping. This validation checks to see if any of the collection of toppings for the Pizza instance evaluates to false. If so, the error message is added.
class Pizza < ApplicationRecord
if topping_collection == false
self.errors[:base] << "Please select at least one topping"
self.mozzarella || self.basil || self.mushrooms
This validation ensures that when a Pizza is created with at least one topping.