我有这些模型:
class Relationship < ActiveRecord::Base
belongs_to :student
belongs_to :guardian
end
class Student < ActiveRecord::Base
has_many :relationships
has_many :guardians, through: :relationships
end
class Guardian < ActiveRecord::Base
has_many :relationships
has_many :students, through: :relationships
end
我不希望任何监护人与一名学生多次相关。这可以通过验证来防止,但是让我们说它为时已晚,并且有可能发生这种情况。例如,g
是监护人:
g.relationships
[
[0] #<Relationship:0x0000000bc33650> {
:id => 40321,
:relationship_type_id => 2,
:student_id => 41700,
:guardian_id => 45820,
:created_at => Tue, 23 Apr 2013 17:44:29 UTC +00:00,
:updated_at => Tue, 23 Apr 2013 17:44:29 UTC +00:00,
},
[1] #<Relationship:0x0000000bc32e80> {
:id => 40923,
:relationship_type_id => 2,
:student_id => 41700,
:guardian_id => 45820,
:created_at => Tue, 23 Apr 2013 18:58:46 UTC +00:00,
:updated_at => Tue, 23 Apr 2013 18:58:46 UTC +00:00,
}
]
如您所见,这两个关系共享同一个student_id。我想知道是否有一种方法可以从数据库中删除重复的关系。我尝试了以下代码行无济于事:
g.relationships.uniq!(&:student_id)
g.update_attributes(relatioships: g.relationships.uniq!(&:student_id))
我该如何解决这个问题。谢谢!
答案 0 :(得分:0)
subquery = Relationship.select("student_id, guardian_id").
group(:student_id, :guardian_id).
having("count(*) > 1").to_sql
groups = Relationship.joins("JOIN (#{subquery}) sub ON relationships.student_id = sub.student_id AND relationships.guardian_id = sub.guardian_id").
group_by{|r| [r.student_id, r.guardian_id] }
groups.values.each do |duplicates|
duplicates.drop(1).each(&:destroy)
end