Ruby on rails 在中添加级别有许多关联rails
在我的rails应用程序中,州和医院之间有关联。 一个州有许多医院,一个医院属于一个州。 所以 因此,我的医院表中有一个state_id列。 现在,由于一些要求,我需要在这个协会中添加一个层次结构,即一个新的模型城市。 一个州有很多城市,一个城市有很多医院,所以一个州有很多医院 我的模特现在应该喜欢这个-Ruby on rails 在中添加级别有许多关联rails,ruby-on-rails,associations,has-many-through,has-many,Ruby On Rails,Associations,Has Many Through,Has Many,在我的rails应用程序中,州和医院之间有关联。 一个州有许多医院,一个医院属于一个州。 所以 因此,我的医院表中有一个state_id列。 现在,由于一些要求,我需要在这个协会中添加一个层次结构,即一个新的模型城市。 一个州有很多城市,一个城市有很多医院,所以一个州有很多医院 我的模特现在应该喜欢这个- class State < ActiveRecord::Base has_many :cities has_many :hospitals, through: :cities e
class State < ActiveRecord::Base
has_many :cities
has_many :hospitals, through: :cities
end
class Hospital < ActiveRecord::Base
belongs_to :city
end
class City < ActiveRecord::Base
has_many :hospitals
belongs_to :state
end
如果我想运行像@state.hospitals这样的查询,那么模型中的这种更改会起作用吗
另外,我的应用程序已经使用State\u id列为State 1…n Hospitals association填充了数据。如何在两者之间添加此模型并保持数据正常
我是rails新手,非常感谢您的帮助。
谢谢
class State < ActiveRecord::Base
has_many :cities
has_many :hospitals, through: :cities
end
class Hospital < ActiveRecord::Base
belongs_to :city
end
class City < ActiveRecord::Base
has_many :hospitals
belongs_to :state
end