Zack Herbert
Zack Herbert

Reputation: 960

Set default value based on column in another table during migration

Trying to change my database a little bit. I have two tables one called User and one called Plan. I want to perform a migration that will add a column to my User table and set the default value of that column based on the value of a column in the Plan table. Then drop the Plan table along with any other columns in the User table that were associated with Plan. The following is the code that I have so far, but I am not sure if it is the best approach.

class DropPlansAddPurchasedAuctionsToCompany < ActiveRecord::Migration
  def up
    add_column :users, :purchased_items, :integer, default: 0, after: :legal_name
    User.update_all(:purchased_items => -1).where("plan_id IS NOT NULL")
    remove_column :users, :plan_id
    remove_column :users, :plan_started_at
    remove_column :users, :disable_plan_limits
    drop_table :plans
  end

  def down
    raise ActiveRecord::IrreversibleMigration, "Can't recover plans table"
  end
end

I think this is the right direction but when I run the migration i get the following error message: NoMethodError: undefined method 'where' for 3:Fixnum

Any insight or suggestions? If you need more info I can provide it.

Upvotes: 0

Views: 797

Answers (1)

eugen
eugen

Reputation: 9226

update_all returns the number of records that were updated, which is a number, not a relation. You should do the where before the update_all:

User.where("plan_id IS NOT NULL").update_all(:purchased_items => -1)

Upvotes: 1

Related Questions