class AddRatingToRecipe < ActiveRecord::Migration[5.0] class Recipe < ActiveRecord::Base end class Log < ActiveRecord::Base end def change add_column :recipes, :rating, :float Recipe.reset_column_information Log.reset_column_information Recipe.all.each do |r| r.rating = Log.where(user_id: r.user_id).where(source_recipe_id: r).where('rating IS NOT NULL').average(:rating) r.save! end end end