Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Restoring a has many through record automatically? #437

Open
jhubert opened this issue Apr 5, 2018 · 1 comment
Open

Restoring a has many through record automatically? #437

jhubert opened this issue Apr 5, 2018 · 1 comment
Labels

Comments

@jhubert
Copy link

jhubert commented Apr 5, 2018

Let's say you have the following setup:

class User < ActiveRecord::Base
  has_many :team_memberships, dependent: :destroy
  has_many :teams, through: :team_memberships, dependent: destroy
end

class TeamMembership < ActiveRecord::Base
  acts_as_paranoid

  belongs_to :team
  belongs_to :user

  validates :team, uniqueness: { scope: :user }
end

class Team < ActiveRecord::Base
  has_many :team_memberships, dependent: :destroy
  has_many :users, through: :team_memberships, dependent: :destroy
end

In addition, you have a database level unique index to make sure team and user only have 1 team membership, similar to the validation on team membership.

The following will produce a database not-unique error:

team = Team.find(1)
user.teams << team
user.teams.delete(team)
user.teams << team

That doesn't seem like the right behavior. I've solved this with a hack in our code, but I wanted to figure out what other people thought was the right behavior before going further.

Is it:

a. We're stupid for having a unique validation on a soft deleted column. Remove it and just create duplicate team memberships.
b. The error is valid and reasonable because we should have identified and restored the previous record before trying to add a new one.
c. We should find and restore the original team membership instead of creating a new one

@kamilbednarz
Copy link

Hey @jhubert I'm struggling with similar issue (Rails 4.2 here).

So far I narrowed it down to the change made in ActiveRecord 4.2.4:
rails/rails@449241c

As far as I understand, ActiveRecord drops default scope queries in the through associations, which results with returning deleted records.

Something that helped in our case was to monkey patch the code from the link I referenced above and reverting this change.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants