Last active
July 5, 2017 20:10
-
-
Save scmx/8859531 to your computer and use it in GitHub Desktop.
Removing duplicate records Rails 4 #rails4, #uniqueness, #accepts_nested_attributes_for
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Related article | |
# http://robots.thoughtbot.com/accepts-nested-attributes-for-with-has-many-through | |
# Pluck ids | |
arr = CompanyEmployment.pluck(:company_id, :company_user_id) | |
#=> [[1,1], [1,2], [2,1], [2,1]] | |
# Select duplicates http://stackoverflow.com/a/8922408/2037928 | |
dups = arr.select {|e| arr.rindex(e) != arr.index(e) }.uniq | |
#=> [[2,1]] | |
# Find these records and destroy them | |
dups.each{|d| CompanyEmployment.find_by(company_id: d[0], company_user_id: d[1]).destroy } | |
# Example setup | |
class Company < ActiveRecord::Base | |
has_many :company_employments, inverse_of: :company | |
end | |
class CompanyUser < ActiveRecord::Base | |
has_many :company_employments | |
end | |
class CompanyEmployment < ActiveRecord::Base | |
belongs_to :company | |
belongs_to :company_user | |
accepts_nested_attributes_for :company_user | |
validates :company, presence: true | |
validates :company_user, presence: true | |
validates :company_user_id, uniqueness: { scope: :company_id } | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment