Ruby 关于 Rails 数据 Table 设置

Ruby on Rails Data Table Setup

我目前正在尝试创建一个跟踪用户旅行的应用程序。理想情况下,我希望用户能够访问他们访问过的 select 个国家/地区,然后能够访问 select 个他们访问过的国家/地区中的 select 个城市。

在测试场景的初始设置中,我能够通过 Trip 模型在用户模型和国家/地区模型之间建立多对多关系。当我尝试添加城市模型并进行设置时,我感到很困惑。我知道它与 Country 模型(示例 belongs_to :country)具有一对多关系,与 users 模型具有多对多关系。我不想要的是用户能够在不首先分配国家的情况下分配城市。这看起来很简单,我假设我必须进行某种验证才能使这种情况起作用,但是我找不到满足我需求的确切答案。

如有任何帮助,我们将不胜感激。

这只是关于你的案例的一个想法,如果你通过旅行模型在用户和城市之间设置多对多,然后在国家到城市之间设置一对多,怎么样?

class User < ActiveRecord::Base
  # -> trips -> cities
  has_many :trips, :dependent => :destroy
  accepts_nested_attributes_for :trips,   :allow_destroy => :true  
  has_many :cities, through: :trips
end

class Trip < ActiveRecord::Base
  belongs_to :User
  belongs_to :City
end

class City < ActiveRecord::Base
  # -> trips -> users
  has_many :trips, :dependent => :destroy
  accepts_nested_attributes_for :trips,   :allow_destroy => :true  
  has_many :users, through: :trips
  # ->  
  belongs_to :Country
end

class Country < ActiveRecord::Base
  # -> cities
  has_many :cities, :dependent => :destroy
  accepts_nested_attributes_for :cities,   :allow_destroy => :true  
end