0

I have two basic models:

class Case < ActiveRecord::Base
 has_many :contacts
end

class Contact < ActiveRecord::Base
 belongs_to :case
 belongs_to :contactable, :polymorphic => true, :foreign_key => :contactable_id
end

I also have quite a few models that are "sub types" of the Contact model:

class Attorney < ActiveRecord::Base
 has_one :contact, as: :contactable, dependent: :destroy

 accepts_nested_attributes_for :contact
end


class Client < ActiveRecord::Base
 has_one :contact, as: :contactable, dependent: :destroy

 accepts_nested_attributes_for :contact
end

I used polymorphic associations instead of STI because I don't want one table to store all the fields, which can get a little slow and overwhelming.

I am wondering if the has_many :contacts line from the Case model is correct. I try to use it in my console, but it doesn't really work the way I expected. Am I missing something?

I basically want an association where a Case can have many Contacts and a contact can belong to many cases. The contact can be of any type (Attorney or Client or Contact by itself). I was hoping it was as easy as case has_many :contacts

Rav Johal
  • 374
  • 2
  • 14
  • You are forgetting a `:` at `belongs_to case`. Is it like that in your code or just a typo in the question? – Biketire Aug 19 '14 at 09:50
  • typo in the question – Rav Johal Aug 19 '14 at 09:52
  • You want to be able to have *many* `contacts`, belong to *many* `cases`. Which is a many-to-many relation. Right now you have written a one-to-many relation. What you want is a `has many .. through` relation. See http://guides.rubyonrails.org/association_basics.html – Biketire Aug 19 '14 at 09:56
  • So am I just treating the Contacts model as any other model? I can use that has_many :through association in place of habtm (which I had intended to do). I was just wondering since Contact is a polymorphic model if I have to do anything different – Rav Johal Aug 19 '14 at 09:58
  • Yes. You have to create a 'link-table' between cases and contacts. Probably case-contacts which holds a `case_id` and a `contact_id`. – Biketire Aug 19 '14 at 10:03
  • I just did a quick search on habtm and polymorphic and this is what I found: [link](http://stackoverflow.com/questions/17280793/rails-habtm-with-polymorphic-relationships) ... I think I can substitute Case for Category and Contact for Categorization? – Rav Johal Aug 19 '14 at 10:07
  • Yes that is possible – Biketire Aug 19 '14 at 12:47

0 Answers0