Ruby on Rails has_many和多态 [英] Ruby on Rails has_many and polymorphism
问题描述
我是Ruby on Rails的新手,并且试图了解抽象类.也许我还记得Java结构...
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...
推荐答案
以下是您的问题的解决方案:
Here is a solution for your problem :
您的Person
和Company
必须是belongs_to
通讯簿.
Addressbook
has_many
:persons
和has_many
:companies
.
Addressbook
has_many
:person_addresses
和has_many
:company_addresses
(使用:through
)
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
)
之后,您可以定义一个函数addresses
,它是person_addresses
和company_addresses
的并集.
After, you can define a function addresses
, which is the union of person_addresses
and company_addresses
.
另一种解决方案是声明Person
和Company
的超类,例如,命名为Addressable
.我认为这是一种更漂亮的方式.
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
这篇关于Ruby on Rails has_many和多态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!