Use belongs_to association in Rails 4

99 views Asked by At

I am reading the docs, and they say about belongs_to:

Specifies a one-to-one association with another class. This method should only be used if this class contains the foreign key.

I have 3 models:

Info
Customer
Seller

I need that every instance of Customer or Seller can be linked to one row in the infos table.

So I think I just need to put the foreing_key info_id in the 2 models, and specify a belongs_to :info association.

But when I do this:

@customer.info 

It gives me error because is trying to execute this query:

SELECT  `auth_infos`.* FROM `auth_infos` WHERE `auth_infos`.`customer_id` = 1 LIMIT 1

But for what I need and what I underatand from the docs it should execute this one:

SELECT  `auth_infos`.* FROM `auth_infos` WHERE `auth_infos`.`id` = 1 LIMIT 1

What am I missing?

3

There are 3 answers

1
Pardeep Dhingra On

You should do it like

info model

has_one :customer
has_one :seller

customer model

belongs_to :info

seller model

belongs_to :info

model having belongs_to always contain foreign key. So customer and seller table will have info_id foreign keys.

info_id

After that you can get both customer and seller linked with info and vice versa.

@customer.info
@info.customer
@seller.info
@info.seller
0
David Aldridge On

The docs express the relationship incorrectly. "Belongs_to" doesn't state anything about the cardinality of the other model, only that whatever the other model is, it can only have zero or one of whatever "belongs_to" it.

If ...

Price belongs_to Book
Book  has_one Price

... then a book can have zero or one prices, and a price can only belong to one book.

If ...

Price belongs_to Book
Book  has_many Price

... then a book can have zero or many prices, and again a price can only belong to one book.

If a Customer or a Seller can optionally have at most one Info, and onfo can have either zero or one Customer or Seller, then make Info polymorphic and let Customer and Seller "has_one informable" (or similar). Then Info "belongs_to informable"

1
Ankita Tandel On

You can use polymorhic association. make Info model polymorhic.

info.rb

class Info < ActiveRecord::Base

  belongs_to :informable, polymorphic: true

end

customer.rb

class Customer < ActiveRecord::Base

  has_one :info, as: :informable

end

seller.rb

class Seller < ActiveRecord::Base

  has_one :info, as: :informable

end