Bradley Oesch
Bradley Oesch

Reputation: 763

Rails belongs_to many but parent only has_one

I have three models, interaction, contact, and company. A company has_many contacts, and an interaction has_one contact, and a contact can belong_to one company but can belong_to many interactions. How can I represent that in rails?

It makes sense that a contact has the company_id and an interaction has the contact_id, but then you can't call interaction.contact because rails sees that as

SELECT "contacts".* FROM "contacts" WHERE "contacts"."interaction_id" = $1 LIMIT 1

where $1 is my contact_id in interaction which doesn't do what I want, which is something like

SELECT "contacts".* FROM "contacts" WHERE "contacts"."id" = $1 LIMIT 1

Upvotes: 0

Views: 22

Answers (1)

jlhonora
jlhonora

Reputation: 10699

This arrangement fits your use case:

class Company

  has_many :contacts

end

class Contact

  belongs_to :company
  has_many :interactions

end

class Interaction

  belongs_to :contact

end

You could also explore bi-directional associations, but that's more of an advanced topic.

Upvotes: 1

Related Questions