Skip to content

Instantly share code, notes, and snippets.

@cassiomarques
Created March 4, 2012 04:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cassiomarques/1970727 to your computer and use it in GitHub Desktop.
Save cassiomarques/1970727 to your computer and use it in GitHub Desktop.
# For example, in a migration
#
# create_check_with_enumeration :foobars, :column => :category, :with => FoobarsCategory
#
# will create a check constraint in the table "foobars", so the column "category" will only accept one
# of the values declared in the FoobarsCategory enumeration
#
module ActiveRecord
module ConnectionAdapters
class PostgreSQLAdapter < AbstractAdapter
def create_check_with_enumeration(table, options)
options.assert_valid_keys :column, :with
[:column, :with].each { |opt| raise "You must pass an #{opt} option" if options[opt].blank? }
list = options[:with].list.map { |v| v.is_a?(String) ? "'#{v}'" : v }.join(", ")
execute %Q{alter table #{table} add constraint #{table}_#{options[:column]}_check check (#{options[:column]} in (#{list}))}
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment