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??
CodePudding user response:
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
CodePudding user response:
You probably shouldn't be directly creating associations by creating UserProject
objects.
Instead, assign users to projects with Project.find(1).users << User.find(1)
It appears that this will not duplicate assignments. I tried on a couple of associations and the assignments don't duplicate. Does it work for you?