Rails: Mehrere "Has_Many durch" für die beidenselben Modelle?
-
23-09-2019 - |
Frage
Ich kann meinen Kopf nicht um dieses ...
class User < ActiveRecord::Base
has_many :fantasies, :through => :fantasizings
has_many :fantasizings, :dependent => :destroy
end
class Fantasy < ActiveRecord::Base
has_many :users, :through => :fantasizings
has_many :fantasizings, :dependent => :destroy
end
class Fantasizing < ActiveRecord::Base
belongs_to :user
belongs_to :fantasy
end
... was gut für meine primäre Beziehung funktioniert, darin a User
kann haben viele Fantasies
, und das a Fantasy
kann gehören zu vielen Users
.
Ich muss jedoch eine weitere Beziehung für hinzufügen Geschmack (wie in, a User
"Likes" a Fantasy
Anstatt "hat" es ... denken Sie an Facebook und wie Sie "einen Mauerposten mögen können, obwohl es Ihnen nicht" gehört "... tatsächlich ist das Facebook-Beispiel fast genau das, was ich ' M zielen auf).
Ich habe festgestellt, dass ich einen weiteren Zusammenhang annehmen sollte, aber ich bin ein bisschen verwirrt darüber, wie ich es benutze oder ob dies sogar der richtige Ansatz ist. Ich fügte zunächst Folgendes hinzu:
class Fantasy < ActiveRecord::Base
...
has_many :users, :through => :approvals
has_many :approvals, :dependent => :destroy
end
class User < ActiveRecord::Base
...
has_many :fantasies, :through => :approvals
has_many :approvals, :dependent => :destroy
end
class Approval < ActiveRecord::Base
belongs_to :user
belongs_to :fantasy
end
... aber wie schaffe ich die Assoziation durch Approval
eher als durch Fantasizing
?
Wenn mich jemand direkt darauf einstellen könnte, wäre ich sehr verpflichtet!
Lösung
Halten Sie Ihren ersten Code -Satz und fügen Sie in Ihrem Benutzermodell hinzu:
has_many :approved_fantasies, :through => :fantasizings, :source => :fantasy, :conditions => "fantasizings.is_approved = 1"
Fügen Sie in Ihrer FantaSizing -Tabelle ein IS_ -anerkanntes Boolesche Feld hinzu.