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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With