Rails / ActiveRecord has_many through: Zuordnung zu nicht gespeicherten Objekten

Lass uns mit diesen Klassen arbeiten:

class User < ActiveRecord::Base
    has_many :project_participations
    has_many :projects, through: :project_participations, inverse_of: :users
end

class ProjectParticipation < ActiveRecord::Base
    belongs_to :user
    belongs_to :project

    enum role: { member: 0, manager: 1 }
end

class Project < ActiveRecord::Base
    has_many :project_participations
    has_many :users, through: :project_participations, inverse_of: :projects
end

A user kann an vielen teilnehmenprojects mit einer Rolle alsmember oder einmanager. Das Verbindungsmodell heißtProjectParticipation.

Ich habe jetzt ein Problem mit den Zuordnungen für nicht gespeicherte Objekte. Die folgenden Befehle funktionieren so, wie ich denke, dass sie funktionieren sollten:

# first example

u = User.new
p = Project.new

u.projects << p

u.projects
=> #<ActiveRecord::Associations::CollectionProxy [#<Project id: nil>]>

u.project_participations
=> #<ActiveRecord::Associations::CollectionProxy [#<ProjectParticipation id: nil, user_id: nil, project_id: nil, role: nil>]>

So weit so gut - AR hat das @ erstelProjectParticipation von selbst und ich kann auf die @ zugreifprojects einesuser mitu.projects.

Aber es funktioniert nicht wenn ich das @ erstelProjectParticipation alleine

# second example

u = User.new
pp = ProjectParticipation.new
p = Project.new

pp.project = p # assign project to project_participation

u.project_participations << pp # assign project_participation to user

u.project_participations
=> #<ActiveRecord::Associations::CollectionProxy [#<ProjectParticipation id: nil, user_id: nil, project_id: nil, role: nil>]>

u.projects
=> #<ActiveRecord::Associations::CollectionProxy []>

Warum sind die Projekte leer? Ich kann über @ nicht auf die Projekte zugreifu.projects wie früher

Aber wenn ich direkt durch die Beteiligungen gehe, erscheint das Projekt:

u.project_participations.map(&:project)
=> [#<Project id: nil>]

Sollte es nicht direkt wie im ersten Beispiel funktionieren:u.projects Alle Projekte zurücksenden, unabhängig davon, ob ich das Join-Objekt selbst erstellt habe oder nicht? Oder wie kann ich AR darauf aufmerksam machen?

Antworten auf die Frage(4)

Ihre Antwort auf die Frage