Search code examples
ruby-on-railsrubyruby-on-rails-5many-to-manyhas-many-through

Many to Many relationship creating same multiple records in rails


I am current working on a project that includes models like (projects and users). Both of these models has many-to-many association which is done through has_many_through approach.

My third model is UserProject which is model joining these two (Project, Users). Ideally when someone create a record in UserProject model, like if user_id is 1 and project_id is 1, record should be created but whenever someone tries to make the record with the same user_id and project_id, it should not be created.

This is the basic principle of m*n relationship in dbms. We know rails generates unique id for every model record, so at this time record is creating every single time someone creates. Is there any solution to this??


Solution

  • You can apply uniqueness validation in your model with :scope option

    class UserProject < ApplicationRecord
      validates :user_id, uniqueness: { scope: :project_id }
    end
    

    And also is good idea to make DB constraint

    class UniqueUserAndProjects < ActiveRecord::Migration
      def change
        change_table :user_projects do |t|
          t.index %i[user_id project_id], unique: true
        end
      end
    end