Rails 4 Postgres Array attribute: how can I ensure that the attribute is an array during validation?

Hi,

I just started experimenting with the native Postgress array type in Rails 4, and I’m running into an issue I can’t figure out. I want the app to raise an error if the value for an array attribute is not an array.

Before, when I was using a regular text type for the field, and serializing it with Rails, I was able to make sure the attribute was an array with a custom validation like this:

def format_of_admin_email regexp = /.+@.+\..+/i if admin_emails.present? && (!admin_emails.is_a?(Array) || admin_emails.detect { |a| a.match(regexp).nil? }) errors[:base] << "admin_emails must be an array of valid email addresses" end end

But now that the field is a Postgres array, it seems like Rails automatically converts the string input into an empty array, so the validation never fails. Here’s my migration:

class AddAdminEmailsToLocations < ActiveRecord::Migration def change add_column :locations, :admin_emails, :text, array: true end end

If I create a Location where admin_emails is a string:

Location.create!(admin_emails: "this should fail")

it doesn’t raise a validation error, and it sets admin_emails to an empty array.

Am I doing something wrong or is this a bug in Rails?

I also tried checking if the input is an array in a before_validation callback, and added a puts admin_emails.present?, but it returned false, as if it never saw the String input.

Try adding return false

Thanks,

Jordon Bedwell