Reputation: 27852
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
Reputation: 2380
I guess it should be:
has_many :tickets, foreign_key: "ref_token"
belongs_to :user, foreign_key: "token"
Upvotes: 3