我是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
发布评论