Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between foreign_key and primary_key when defining an ActiveRecord association?

I am trying to understand the difference between foreign_key and primary_key when defining an association on an ActiveRecord model. Do you need to use both? What is the difference?

class SomeModel < ActiveRecord::Base
  has_one :something_else, foreign_key: 'some_id', primary_key: 'some_id'
end

class SomethingElse < ActiveRecord::Base
  self.primary_key = 'some_id'
  belongs_to :some_model, foreign_key: 'some_id', primary_key: 'some_id'
end
like image 431
Andrew Avatar asked Oct 26 '25 19:10

Andrew


1 Answers

primary_key defines the name of the database field to be used as primary key instead of the default id.

foreign_key defines the name of the database field which keeps references to the primary key field of another model.

See Active Record Associations docs for more.

If you want conceptual understanding on the role of primary and foreign keys, here is one writeup on this topic.

like image 139
Nic Nilov Avatar answered Oct 29 '25 10:10

Nic Nilov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!