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.
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.
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)")
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.