Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Belongs_to primary key?

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?

like image 640
andy Avatar asked Oct 11 '13 08:10

andy


People also ask

What is the difference between Has_one and Belongs_to?

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.

What is Activerecord in Ruby on Rails?

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.

Does rails have one relationship?

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.


1 Answers

Options should be the same as in has_many :leads association:

belongs_to :user, foreign_key: :initials, primary_key: :name
like image 198
Marek Lipka Avatar answered Sep 28 '22 19:09

Marek Lipka