Skip to content

Instantly share code, notes, and snippets.

@Papierkorb
Created September 20, 2015 16:15
Show Gist options
  • Save Papierkorb/5b660e464ca424b3a562 to your computer and use it in GitHub Desktop.
Save Papierkorb/5b660e464ca424b3a562 to your computer and use it in GitHub Desktop.
Rails migration helper code for updating model concern-specific columns
# Helper methods for writing migrations for concern specific things.
module ConcernHelper
# Returns an array of symbols containing the table names of all models
# including 'concern'. If a block is given, it's called for each table name.
#
# Example usage:
# class AddSomethingToAllFooables
# include ConcernHelper
#
# def change
# each_including_concern Fooable do |table|
# add_column table, :something, :string
# end
# end
# end
#
def each_including_concern(concern, &block)
Rails.application.eager_load!
symbols = ActiveRecord::Base.descendants
.select{|klass| klass.superclass == ActiveRecord::Base}
.select{|klass| klass.include? concern}
.map(&:table_name).map(&:to_sym)
symbols.each(&block) if block_given?
symbols
end
# Delegate helper to check if a certain table already has a certain column.
def column_exists?(table, column)
ActiveRecord::Base.connection.column_exists? table, column
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment