PlankTon
PlankTon

Reputation: 12605

Rails ActiveRecord: 2 associations to same model

I have a model, Project, which has two belongs_to associations to the same model:

belongs_to :source_connection, class: Connection
belongs_to :destination_connection, class: Connection

But on the other side, each connection should have only one association to the project. Adding

has_one :project, foreign_key_id: source_connection_id
or
has_one :project, foreign_key_id: destination_connection_id

Isn't going to cut it, because the connection itself has no knowledge of whether it's a source or destination connection.

Clearly there's a flaw in how I've designed this association, I'm just curious as to what the right way to go about it is. It's worth mentioning that 'Connection' has a lot of inheriting classes (SSHConnection, S3Connection, etc), so splitting the Connection class into 'Source' and 'Destination' Connection models would cause a lot of duplication.

Any thoughts welcome.

Upvotes: 0

Views: 111

Answers (2)

Tom Davies
Tom Davies

Reputation: 1890

As of Rails 4.2.5, the syntax for named associations has changed slightly from that in the accepted answer, the new version would be:

has_one :source_project, class_name: "Project", foreign_key: :source_connection_id
or
has_one :destination_project, class_name: "Project", foreign_key: :destination_connection_id

Upvotes: 0

steel
steel

Reputation: 12520

You're close! You could redesign, or you could try naming the projects differently for the different connection types:

has_one :source_project, class: "Project", foreign_key_id: source_connection_id
or
has_one :destination_project, class: "Project", foreign_key_id: destination_connection_id

This allows you to call @connection.source_project to get the project for which that connection is a source connection, for example. There may be a clearer way to name this for your goals.

Upvotes: 1

Related Questions