Eric Baldwin
Eric Baldwin

Reputation: 3491

SQLite3::ConstraintException: constraint failed: INSERT INTO Join model in Rails

In my model, projects have and belong to many users, so there is a join table projects_users for them. When I insert the line

@project.members += User.find params[:member_ids].split(',')

into the create action of the Projects controller, I cannot save @project. When I try, I get the following error:

SQLite3::ConstraintException: constraint failed: INSERT INTO "projects_users" ("project_id", "user_id") VALUES (5, 14600)

However, just before the save, @project is valid and @project.members returns the correct members. What am I doing wrong?

Upvotes: 1

Views: 1552

Answers (1)

Jim Stewart
Jim Stewart

Reputation: 17323

It sounds like you might have a unique constraint on the DB column that doesn't allow duplicate project_id and user_id pairs in projects_users, but Rails isn't aware of it, so the validations pass, but the actual save fails.

If that's the case, you can use a has_many through relationship and a model for the join table and validate the uniqueness. I suspect you're already doing part of that of that. Something like this might help:

class Project < ActiveRecord::Base
  has_many :members
  has_many :users, through: :project_membership
end

class User < ActiveRecord::Base
  has_many :projects, through: :project_membership
end

class ProjectMembership < ActiveRecord::Base
  self.table_name = "projects_users"
  belongs_to :project
  belongs_to :user
  validates :project_id, uniqueness: { scope: :user_id }
end

You might want to rename your projects_users table if this all works out, to something like project_memberships as in the example above; then you could ditch the self.table_name.

Upvotes: 1

Related Questions