0

ListingモデルとCountryモデルがあります。各リストには国がありますが (住所の詳細の一部として)、各リストには複数の ExportCountries (リストの所有者が輸出する国) を含めることもできます。

A listing has_one country

A Country has_many listings

A listing has_and_belongs_to_many ExportCountries

An ExportCountry has_and_belongs_to_many Listings

2 つの別々のモデルがある場合、おそらく次のようにします。

class Listing < ActiveRecord::Base
  belongs_to :country
  has_and_belongs_to_many :export_countries  
end

class Country < ActiveRecord::Base
  has_many: listings
end

class ExportCountry < ActiveRecord::Base
  has_and_belongs_to_many :listings
end

しかし、たった 1 つの Country モデルでそれを行うにはどうすればよいでしょうか。そうしないと、ExportCountry はまったく同じレコードを持ち、あまり DRY ではなく、Rails のようには見えないからです。

4

1 に答える 1

1

必要なのは、最終結果と同じクラスを持つ2つの別個の関連付けです。次のように正しく解釈できるように、関連付けでそれらを指定する必要があります。

class Country < ActiveRecord::Base
  has_many :address_listings, class_name: "Listing", :foreign_key => "address_country_id"
  has_and_belongs_to_many :export_listings, class_name: "Listing", :join_table => :export_countries_listings
end

class Listing < ActiveRecord::Base
  belongs_to :address_country, class_name: "Country"
  has_and_belongs_to_many :export_countries, class_name: "Country", :join_table => :export_countries_listings
end

address_country_idは、Listingsテーブルの列である必要があります。

そして、輸出国の参加表

create_table :export_countries_listings, :id => false do |t|
  t.integer :country_id
  t.integer :listing_id
end

これにより、アドレスCountryの単一の参照とexport_countriesの多くの参照が設定されます。

于 2013-01-13T18:16:59.883 に答える