问题
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:
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
来源:https://stackoverflow.com/questions/15503913/ruby-on-rails-has-many-and-polymorphism