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

41 views
Skip to first unread message

Moncef Belyamani

unread,
Apr 11, 2014, 11:04:38 AM4/11/14
to rubyonra...@googlegroups.com

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.

Jordon Bedwell

unread,
Apr 11, 2014, 4:28:36 PM4/11/14
to rubyonrails-talk
Try adding `return false`

Thanks,

Jordon Bedwell

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rubyonrails-ta...@googlegroups.com.
To post to this group, send email to rubyonra...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/rubyonrails-talk/f810c395-31a0-49a3-9b14-941d4268e53f%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages