Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate pg array length in Ruby on Rails 5?

How can I validate how many tags my Note model has? My model currently:

# == Schema Information
#
# Table name: notes
#
#  id              :integer          not null, primary key
#  title           :text
#  body            :text
#  organization_id :integer
#  created_at      :datetime         not null
#  updated_at      :datetime         not null
#  tags            :string           default([]), is an Array
#

# Note represents a saved Note that belongs to an organization.
class Note < ApplicationRecord
  belongs_to :organization
  validates :title, :body, presence: true
end

tags is a pg array in the database.

like image 645
Sergio Tapia Avatar asked Jan 02 '17 07:01

Sergio Tapia


People also ask

What is the difference between validate and validates in rails?

So remember folks, validates is for Rails validators (and custom validator classes ending with Validator if that's what you're into), and validate is for your custom validator methods.

How does validate work in Rails?

Rails validation defines valid states for each of your Active Record model classes. They are used to ensure that only valid details are entered into your database. Rails make it easy to add validations to your model classes and allows you to create your own validation methods as well.


1 Answers

Rails will handle conversion internally so you only need to worry about working with a Ruby array object.

Validation looks like this:

class Note < ApplicationRecord
  validates :tags, length: {
    maximum: 10,
    message: 'A note can only have a maximum of 10 tags'
  }
end

it 'is invalid with more than 10 tags' do
  tags = %w(1 2 3 4 5 6 7 8 9 10 11)
  note = build(:note, tags: tags)
  note.valid?
  expect(note.errors[:tags])
    .to include('A note can only have a maximum of 10 tags')
end
like image 72
Sergio Tapia Avatar answered Nov 01 '22 17:11

Sergio Tapia