Skip to content

Instantly share code, notes, and snippets.

@deanrad
Created September 11, 2009 08:57
Show Gist options
  • Save deanrad/185167 to your computer and use it in GitHub Desktop.
Save deanrad/185167 to your computer and use it in GitHub Desktop.
# Alternative to add_column that will do nothing if a column by that name exists already
# Ensures a column of the name will exist - either creating it or leaving the existing one be
# Looks up the table_name in AR::Base's descendants to query them whether this column exists (by name) yet
# Currently does not ensure that the options for the column are the same, nor ensure all models are loaded
def self.ensure_column tn, cn, *opts
klass = begin
@@tables_to_classes ||=
ActiveRecord::Base.class_eval{ subclasses }.inject({}) do |map, this_class|
map[this_class.table_name] = this_class
map
end
@@tables_to_classes[tn]
rescue
nil
end
# only add if it still needs addin
if klass.nil? || ! klass.columns.map(&:name).include?(cn.to_s)
add_column tn, cn, *opts
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment