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...

1 Answer 1

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
4
  • 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. Mar 19, 2013 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? Mar 19, 2013 at 16:24
  • Just answered my own question, edited your post. It works! :D Mar 19, 2013 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, 2013 at 14:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.