0
我有這些模型刪除重複的關聯:的Rails 3:從數據庫
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))
我該如何解決這個問題。謝謝!
是否有任何規則應該保留哪些副本應該保留(最近的,最早的,其他的),或者它並不重要?另外,你想要SQL或Ruby代碼呢? – PinnyM 2013-04-25 17:05:01
沒有規則,如果有兩種相同的類型,他們中的任何一個都適合我 – sauronnikko 2013-04-25 17:06:06