1

私はRubyonRailsを初めて使用し、抽象クラスを理解しようとしています。多分私はまだJava構造を念頭に置いています...

私は多くのチュートリアルに従いましたが、理解する必要のあることがまだあります。コンタクトブックを作成したいとします。この名簿には、人と会社があります。

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

今のところすべてが正常に機能しています。現在、さまざまなユーザーがいて、それぞれに名簿があります。

class User < ActiveRecord::Base
  has_one :addressbook
end

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

個人または会社に関係なく、すべての住所を一覧表示するにはどうすればよいですか?アルファベット順に表示したいので...

4

1 に答える 1

2

これがあなたの問題の解決策です:

あなたPersonCompanyマストbelongs_toアドレスブック。Addressbook has_many :personshas_many :companies。_ Addressbook has_many :person_addressesおよび(has_many :company_addressesを使用:through

その後、とaddressesの和集合である関数を定義できます。person_addressescompany_addresses

もう1つの解決策は、たとえば名前が付けられたPersonとのスーパークラスを宣言することです。私はそれがよりきれいな方法だと思います。CompanyAddressable

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
于 2013-03-19T15:54:21.590 に答える