Topic: has_many without belongs_to?

Hi there.

I'm new in RoR and Ruby and have question (problem actually) with some unusual mapping with ActiveRecord in RoR.

I have contacts table with some standard columns and owner_id and owner_type columns that should store id and type of it's owner. Owners can be Person, Company, Building, ... Are there any ideas how to make this reusable contact scenario?

Tnx,

Bu

Re: has_many without belongs_to?

Sounds like you want polymorphic association. You already have the "owner_type" column correctly, you just need to set up the associations:

class Contact < ActiveRecord::Base
  belongs_to :owner, :polymorphic => true
end

class Person < ActiveRecord::Base
  has_many :contacts, :as => :owner
end

class Company < ActiveRecord::Base
  has_many :contacts, :as => :owner
end

class Building < ActiveRecord::Base
  has_many :contacts, :as => :owner
end

Railscasts - Free Ruby on Rails Screencasts

Re: has_many without belongs_to?

Hi,

Tnx for your reply. I thought of it in the first place, but than I realized tat it is not good idea to use inheritance only becouse of association. One of OO principles says that database normalization is about data and Object normalization is about behaviour and I agree with that. Also, what if I need inheritance for other reasons? My background is C# and the way I did it in it is using IContactOwner interface that has_many contatcs. Contact in the other hand can have navigability to it's owner as IContactOwner, but in this case it isn't necessary. This example is typical problem for all ORM-s I saw (and I saw and tried few of the most popular), so I always had to do it by hand with ADO and it's really easy and straithforward that way. I just don't know how to do it with ruby (RoR).

Bu

Re: has_many without belongs_to?

Hey, I didn't realize in the first place what you wrote. My mistake. I've just woke up. I'll have to check that :polymorphic and :as story. I don't know how it works.

Bu

Re: has_many without belongs_to?

This is just great!!! None of ORMs I tried could do this that easy. Ruby and RoR keep getting me more and more amazed about them

Tnx again ryanb