2

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
8
  • 1
    What's unclear about the guide? Commented Feb 6, 2020 at 6:00
  • I can't find where it says how to add columns for multiple tables and how to set default => 0 Commented Feb 6, 2020 at 6:22
  • 3
    Have you tried add_column :restaurants, :views, :integer, default: 0? Repeat two times, changing :restaurants to :menus and :dishes? Commented Feb 6, 2020 at 6:27
  • 1
    Its not correct with that command. And I saw somewhere where a migration was using model names as the first argument which also struck me as odd. Commented Feb 6, 2020 at 6:39
  • 1
    "add_column :restaurants, :views, :integer, default: 0" makes an empty migration. The correct way is "AddViewsToTeams views:integer". But that doesn't make it look like the example above where the model is the first argument. And adding default:0 after views:integer just makes it another column instead of making the views default => 0 Commented Feb 6, 2020 at 6:56

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.