Hommer Smith
Hommer Smith

Reputation: 27852

belongs_to with different foreign key as well as primary key in the other table

I have two models:

Ticket and User

A ticket belongs_to a User, and a User has_many Tickets.

The thing here is that I want to associate these two models with:

The ticket has a ref_token column and the User has a token column. So, basically when trying to find the User for a given token (token123), I would expect the following query:

SELECT * FROM tickets WHERE token = 'token123'

How can I set the association to accomplish this (basically I want to specify the columns that set the association. In this case they are different than the primary keys).

I have this now:

User

has_many :tickets, foreign_key: 'ref_token', primary_key: 'token'

Ticket

belongs_to :user, foreign_key: 'ref_token', primary_key: 'token'

And I am able to do user.tickets, but I can't do ticket.user. It keeps returning nil.

Upvotes: 3

Views: 4434

Answers (1)

Sean Magyar
Sean Magyar

Reputation: 2380

I guess it should be:

has_many :tickets, foreign_key: "ref_token"

belongs_to :user, foreign_key: "token"

Upvotes: 3

Related Questions