Rails, has one Country and has many ExportCountries?

梦想与她 提交于 2020-01-06 08:17:25

问题


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).

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

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

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.


回答1:


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 should be a column in the Listings table.

And the join table for the export countries

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

This sets up a single reference for the address Country and many references for the export_countries.



来源:https://stackoverflow.com/questions/14299259/rails-has-one-country-and-has-many-exportcountries

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!