Created
August 7, 2013 22:40
-
-
Save ilude/6179569 to your computer and use it in GitHub Desktop.
ActiveRecord Composite Key Migrations with Rails 3.2.13
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # add the following to the end of your environment.rb file | |
| # monkey patching for the win! | |
| ActiveRecord::ConnectionAdapters::ColumnDefinition.class_eval <<-'EOF' | |
| def to_sql | |
| if name.is_a? Array | |
| column_sql = "PRIMARY KEY (#{name.join(',')})" | |
| else | |
| column_sql = "#{base.quote_column_name(name)} #{sql_type}" | |
| column_options = {} | |
| column_options[:null] = null unless null.nil? | |
| column_options[:default] = default unless default.nil? | |
| add_column_options!(column_sql, column_options) unless type.to_sym == :primary_key | |
| end | |
| column_sql | |
| end | |
| EOF | |
| ActiveRecord::ConnectionAdapters::ColumnDefinition.send(:alias_method, :to_s, :to_sql) | |
| ActiveRecord::ConnectionAdapters::TableDefinition.class_eval <<-'EOF' | |
| def column(name, type, options = {}) | |
| name = (name.is_a? Array) ? name : name.to_s | |
| type = type.to_sym | |
| column = self[name] || new_column_definition(@base, name, type) | |
| limit = options.fetch(:limit) do | |
| native[type][:limit] if native[type].is_a?(Hash) | |
| end | |
| column.limit = limit | |
| column.precision = options[:precision] | |
| column.scale = options[:scale] | |
| column.default = options[:default] | |
| column.null = options[:null] | |
| self | |
| end | |
| EOF | |
| ActiveRecord::ConnectionAdapters::SchemaStatements.class_eval <<-'EOF' | |
| def create_table(table_name, options = {}) | |
| td = table_definition | |
| yield td if block_given? | |
| if(options[:id] || options[:primary_key]) | |
| td.primary_key(options[:primary_key] || Base.get_primary_key(table_name.to_s.singularize)) | |
| end | |
| if options[:force] && table_exists?(table_name) | |
| drop_table(table_name, options) | |
| end | |
| create_sql = "CREATE#{' TEMPORARY' if options[:temporary]} TABLE " | |
| create_sql << "#{quote_table_name(table_name)} (" | |
| create_sql << td.to_sql | |
| create_sql << ") #{options[:options]}" | |
| execute create_sql | |
| end | |
| EOF |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| create_table "CARRIER", :primary_key => [:ID], :id => false, :force => true do |t| | |
| t.string "ID", :limit => 15, :null => false | |
| t.string "NAME", :limit => 50 | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment