0

I have a join table that joins students HABTM students

Unfortunately, it's gotten some duplicate records in it.

How can I deduplicate the join table. Ideally, using Ruby.

Will
  • 4,498
  • 2
  • 38
  • 65
  • 2
    do you have a model for the join table or are you using the default Rails' `has_and_belongs_to_many` functionality? – MrYoshiji Feb 14 '18 at 18:56

2 Answers2

0

You can use below query to delete duplicate records from HABTM table.

ActiveRecord::Base.connection.execute("DELETE FROM TableName WHERE (model_id_one, model_id_two) IN (SELECT model_id_one model_id_two FROM TableName GROUP BY model_id_one, model_id_two HAVING COUNT(*) > 1)")

Prince Bansal
  • 286
  • 2
  • 5
0

I think it will help: has_and_belongs_to_many, avoiding dupes in the join table

For showing related entries without duplicates:

has_and_belongs_to_many :students, -> { distinct }

But also I recommend to add unique index on your join table.

  • no this isn't right, they are measures to only show unique items, not dedupe the db and the second one prevents the duplicates, which is the next task, that I can't do until it's de-duped. – Will Feb 15 '18 at 17:59