1

I'm new to Ruby on Rails and I'm trying to understand abstract class. Maybe I still have in mind Java structure...

I followed many tutorials and there is still things I'd need to understand. Let's say we want to build a contact book. In this address book, we have people and companies.

class Address < ActiveRecord::Base
  belongs_to :addressable, :polymorphic => true
end

class Person < ActiveRecord::Base
  has_one :address, :as => :addressable
end

class Company < ActiveRecord::Base
  has_one :address, :as => :addressable
end

Everything's working fine for now. Now, we have different users, each one has an address book.

class User < ActiveRecord::Base
  has_one :addressbook
end

class Addressbook < ActiveRecord::Base
  has_many ??????
end

How do i list all the addresses no matter if they are a person or a company? Because i'd like to display them in alphabetical order...

Sophie Déziel
  • 428
  • 2
  • 11

1 Answers1

2

Here is a solution for your problem :

Your Person and Company must belongs_to Addressbook. An Addressbook has_many :persons and has_many :companies. An Addressbook has_many :person_addresses and has_many :company_addresses (using :through)

After, you can define a function addresses, which is the union of person_addresses and company_addresses.

An other solution is to declare a super-class for Person and Company, named Addressable for example. I think it's a prettier way.

class Address < ActiveRecord::Base
  belongs_to :addressable
end

class Addressable < ActiveRecord::Base
  has_one :address
  belongs_to :addressbooks
end

class Person < Addressable
end

class Company < Addressable
end

class User < ActiveRecord::Base
  has_one :addressbook
end

class Addressbook < ActiveRecord::Base
  has_many :addressables
  has_many :addresses, :through => :addressables
end
pierallard
  • 3,326
  • 3
  • 21
  • 48
  • Yes, a super-class seems the best, do you have any hints how i should do it? I'll google it, but i'm not very comfortable diving in those concepts since i'm very new to Rails. – Sophie Déziel Mar 19 '13 at 15:59
  • This works just fine! One last question: is it possible for Person or company to have attributes that the other doesn't have? For example, can a person have an age (not the company) and the company have a founder? – Sophie Déziel Mar 19 '13 at 16:24
  • Just answered my own question, edited your post. It works! :D – Sophie Déziel Mar 19 '13 at 17:05
  • @SophieDéziel Of course you can ! But don't forget to add this specific columns into `Adressable` classes. This columns will be automatically `NULL` in the others types. – pierallard Mar 20 '13 at 14:33