I have a DB layout like so:
Users
--------------
id, name, etc...
Lead
--------------
id, initials, etc..
Basically a user has many leads. The initials
field maps to the name
field in the users table. I have a relationship for the users setup that works perfect:
has_many :leads, :foreign_key => 'initials',
:primary_key => 'name'
But I can't figure out how to do it the other way using belongs_to
:
belongs_to :user, :foreign_key => 'name',
:primary_key => 'initials'
That doesn't seem to work.
Any ideas?
They essentially do the same thing, the only difference is what side of the relationship you are on. If a User has a Profile , then in the User class you'd have has_one :profile and in the Profile class you'd have belongs_to :user . To determine who "has" the other object, look at where the foreign key is.
1 What is Active Record? Active Record is the M in MVC - the model - which is the layer of the system responsible for representing business data and logic. Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database.
A has_one association indicates that one other model has a reference to this model. That model can be fetched through this association. This relation can be bi-directional when used in combination with belongs_to on the other model.
Options should be the same as in has_many :leads
association:
belongs_to :user, foreign_key: :initials, primary_key: :name
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