ruby-on-rails-4mongoid4

Rails check for duplicate models


I did a mistake in my rails app, and I didn't enforce the uniqueness of logins. Now I'd like to clean this mess by finding and removing duplicates (manually) in my code.

Is there a nice command I could enter in the Rails console that would let me find those duplicates ? Eg. find two users with the same login, and maybe make an array of array of duplicates ?


Solution

  • Assuming your model is User and you are looking for duplicate attribute login, you should be able to do something like this:

    User.find_by_sql("SELECT u1.id, u1.login FROM users u1 LEFT JOIN users u2 WHERE u1.login=u2.login AND u1.id!=u2.id ORDER BY u1.login, u1.id")
    

    Of course, you can change the select to include whatever attributes you will need in order to decide what to do about the duplicates.

    EDIT for Mongoid, look at this link