Rails中的自引用映射表

时间:2012-09-19 12:27:39

标签: ruby-on-rails

我正试图解决在小型Rails应用程序中创建Shiping Zones的问题。

数据库列出属于用户的项目,这些项目可以出售给其他用户。两者都可以在全球范围内,他们的原籍国列在location_countries表中。

我目前看到的方式是将有一个运输区域表[id,name,description]和一个映射表[from_country_id,to_country_id,shipping_zone_id],它引用location_countries表两次以确定要使用的区域规则和shipping_zones表(最后引用定价矩阵)。

我遇到的问题是如何在模型文件中表示: location_country可以有多个区域,具体取决于另一个location_country。

在我看来,它应该是直截了当的,但我也觉得我正在解决这个问题。有关这方面的任何指示吗?

1 个答案:

答案 0 :(得分:1)

我建议创建和链接类如下:

class Country

  has_many :from_mappings, :class_name => "Mapping", :foreign_key => :from_country_id
  has_many :from_countries, :through => :from_mappings

  has_many :to_mappings, :class_name => "Mapping", :foreign_key => :to_country_id
  has_many :to_countries, :through => :to_mappings
...

class Mapping

  belongs_to :shipping_zone

  belongs_to :from_country, :class_name => "Country", :foreign_key => :to_country_id
  belongs_to :to_country, :class_name => "Country", :foreign_key => :from_country_id
...

认为应该是一个解决方案,但我可能会误解你问题的某些部分。