Jabba the Hutt
Jabba the Hutt

Reputation: 664

Rails Activerecord adding columns to multiple tables

I need to make a migration where a column is added to three separate tables. The views column is an integer and needs to also default => 0. How can I add these columns with activerecord commands? I am using postgreSQL database.

Here is how my migration should look like:

class AddViewsToRestaurantsMenusDishes < ActiveRecord::Migration[6.0]
   def change
     add_column Restaurant, :views, :integer, :default => 0
     add_column Menu, :views, :integer, :default => 0
     add_column Dish, :views, :integer, :default => 0
   end
end

Upvotes: 2

Views: 1582

Answers (1)

max
max

Reputation: 101821

add_column(table_name, column_name, type, **options)

class AddViewsToRestaurantsMenusDishes < ActiveRecord::Migration[6.0]
   def change
     add_column :restaurants, :views, :integer, default: 0
     add_column :menus, :views, :integer, default: 0
     add_column :dishes, :views, :integer, default: 0
   end
end

None of the methods in ActiveRecord::ConnectionAdapters::SchemaStatements or ActiveRecord::ConnectionAdapters::TableDefinition which make up the whole migrations DSL take models as arguments - its all tables all the way.

This assumes that your tables are conventionally named. If you really wanted to do the same thing from a list of model classes you could do:

class AddViewsToRestaurantsMenusDishes < ActiveRecord::Migration[6.0]
   def change
     [Restaurant, Menu, Dish].each do |model|
       add_column model.table_name, :views, :integer, default: 0
     end
   end
end

But for migrations its usually a good idea to KISS. Especially since they are not supposed to stick around for the entire lifetime of your project.

Upvotes: 3

Related Questions