-1

I have a join table in rails that has a few entries that need to be deleted.

lets say the join table is named 'products_variants'

I found out i have a few entries in this join table that were created erroneously a while ago. I have their IDs, so i could go in phpmyadmin and delete them, but I want to make a migration to do it in case anyone uses an older database (which has happened before).

Since I don't have a ruby object representing this join table I cant do something like:

ProductsVariants.find(id_array)

How would i go about deleting these entries in a rails migration?

Zyren
  • 603
  • 2
  • 7
  • 21
  • Why do you want to delete records before drop table? – Maxim Mar 02 '15 at 17:36
  • I don't want to delete the table. I just want to delete a few entries that shouldn't be there – Zyren Mar 02 '15 at 18:10
  • So, in this case you can create ActiveRecord model inside of your migration as I described below. And use it for clear table use `delete_all` method – Maxim Mar 02 '15 at 18:12
  • 2
    check this SO question http://stackoverflow.com/q/19387440/687142 . It explains whether you should try to do this or not. – xlembouras Mar 02 '15 at 18:26

3 Answers3

0

How would you do it from the console? Whatever that is, put it in the migration. For example

class Cleanup < ActiveRecord::Migration
  def up
    execute("delete from product_variants where id in (1,2,3)")
  end
  def down
  end
end
John Naegle
  • 8,077
  • 3
  • 38
  • 47
0

You can create AR class for this table inside of migration and use it for delete record.

Maxim
  • 9,701
  • 5
  • 60
  • 108
0

Barring a solution like maxd's answer, you can also delete them via plain 'ol SQL. If you already have the list of ids, you can do something like this:

ActiveRecord::Base.connection.execute("DELETE FROM products_variants WHERE id IN (...)")

Where ... is the list of ids to delete.

Semi-pointless side-note: Technically speaking, data manipulation is not typically done in the migrations for various reason; one of them being that you're usually not necessarily guaranteed that all (or even any) migrations will be run by your colleagues (speaking very generally here), or in the case of new local project setups (meaning, you've just pulled down the project code and are setting it up locally for the first time).

While it doesn't sound like this is an issue in your scenario, if you want to do this the Rails-y way, one alternative would be to put this in a Rake task, so that you or others can execute it as needed, rather than relying on the migrations.

Paul Richter
  • 10,908
  • 10
  • 52
  • 85