【问题标题】:Ruby on Rails Data Table Setup [closed]Ruby on Rails 数据表设置 [关闭]
【发布时间】:2017-12-14 10:57:48
【问题描述】:
我目前正在尝试创建一个跟踪用户旅行的应用。理想情况下,我希望用户能够选择他们访问过的国家,然后能够选择他们在他们选择的国家访问过的城市。
在我测试场景的初始设置中,我能够通过 Trip 模型在 User 模型和 Country 模型之间建立多对多关系。当我尝试添加 City 模型并进行设置时,我感到困惑。我知道它将与 Country 模型(例如 belongs_to :country)建立一对多关系,并与 users 模型建立多对多关系。我不希望用户能够在不首先分配国家/地区的情况下分配城市。这看起来很简单,我认为我必须进行某种验证才能使这个场景正常工作,但是我找不到满足我需求的确切答案。
任何帮助将不胜感激。
【问题讨论】:
标签:
ruby-on-rails
ruby
model-view-controller
models
【解决方案1】:
这只是关于你的案例的一个想法,如果你通过旅行模型在用户和城市之间设置多对多,然后在国家到城市之间设置一对多。
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