问题描述
我有一个列表模型和一个国家/地区模型.每个商家信息都有一个国家/地区(作为其地址详细信息的一部分),但每个商家信息也可以有多个出口国家/地区(只是商家信息所有者出口到的国家/地区).
I have a Listing model and a Country model. Each listing has a country (as part of it's address details), but each listing can also have several ExportCountries (which are just countries the listing owner exports to).
一个列表有_一个国家
一个国家有_许多房源
一个列表 has_and_belongs_to_many ExportCountries
ExportCountry has_and_belongs_to_many Listings
如果我有两个独立的模型,我可能会这样做:
If I had two separate models I would probably do this:
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
但是我怎么能只用一个 Country 模型来做到这一点 - 因为否则 ExportCountry 将拥有完全相同的记录,这些记录不是很 DRY,只是看起来不像 Rails.
But how can I do it with just one Country model - because otherwise ExportCountry will have exactly the same records which isn't very DRY and just doesn't seem Rails-like.
推荐答案
您想要的是两个独立的关联,它们具有相同的类作为最终结果.您只需要在关联中指定那些,以便它可以像这样正确解释它们:
What you want is two separate associations with the same class as the end result. You just need to specify those in the associations so that it can interpret them correctly like so:
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 表中的一列.
address_country_id should be a column in the Listings table.
以及出口国家的连接表
create_table :export_countries_listings, :id => false do |t|
t.integer :country_id
t.integer :listing_id
end
这会为地址 Country 设置单个引用,并为 export_countries 设置多个引用.
This sets up a single reference for the address Country and many references for the export_countries.
这篇关于Rails,有一个国家,有许多出口国家?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!