2013-01-13 27 views
0

我有一個代碼模型和一個國家模型。每個列表都有一個國家(作爲其地址詳細信息的一部分),但每個列表還可以有多個ExportCountries(只是列表所有者出口到的國家/地區)。Rails,有一個國家和許多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

如果我有兩個獨立的模型,我可能會做到這一點:

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 

但是,我怎樣才能用一個國家模式來做到這一點 - 因爲否則ExportCountry將具有完全相同的記錄,這不是非常乾燥,並且看起來不像Rails那樣。

回答

1

你想要的是與最終結果相同的兩個單獨關聯。你只需要指定它們的關聯,以便它可以正確地解釋它們像這樣:

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應在清單表中的列。

而對於出口國家

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

連接表這個選項可以設置地址國家和許多的參考export_countries一個參考。

+0

謝謝 - 它的工作原理! – A4J

相關問題