0

I have a user model:

users
-id
-external_id

sales
-id
-external_id

So my models with associations looks like:

class Sale < ApplicationRecord
  belongs_to :user
end

class User < ApplicationRecord
  has_many :sales
end

How can I link the associations through the column 'external_id' ?

Blankman
  • 259,732
  • 324
  • 769
  • 1,199

2 Answers2

1

you can use foreign_key here.

class Sale < ApplicationRecord
  belongs_to :user, foreign_key: :external_id
end

class User < ApplicationRecord
  has_many :sales, foreign_key: :external_id
end
lg86
  • 350
  • 2
  • 7
  • If this is what the OP is looking for, then here is a similar question with more explanation: https://stackoverflow.com/a/904452/2437278 – HighHopes Jan 16 '18 at 04:07
0

I'm not sure if you mean you want the column name to be external_idor if you just are wondering how to get an external id (foreign key). I'm going to assume the latter since this is how a relational db is usually set up. When you make a model, you would do it like this, for example:

rails g model user email:string password:string

rails g model sale user:references amount:decimal

More here

That would create tables that look like this:

Users
email: string
password: string

Sales
user_id: integer
amount: decimal

Where user_id is the foreign key to the user associated with that sale since a user has many sales and a sale belongs to a user.

Remember: the id of the 1 goes on the many.

HighHopes
  • 2,014
  • 3
  • 23
  • 33