0
我有以下型号,无法定义的Active Record协会正确
class City < ActiveRecord::Base
belongs_to :state
belongs_to :country
end
class State < ActiveRecord::Base
belongs_to :country
has_many :cities
end
class Country < ActiveRecord::Base
has_many :states
has_many :cities, :through => :state
end
这是我schema.rb,
create_table "cities", :force => true do |t|
t.string "name"
t.string "state_id"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "countries", :force => true do |t|
t.string "name"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "states", :force => true do |t|
t.string "name"
t.string "country_id"
t.datetime "created_at"
t.datetime "updated_at"
end
这是我的种子数据,
country_in = Country.create(name: 'India')
state_ap = country_in.states.create(name: 'Andhra Pradesh')
state_mh = country_in.states.create(name: 'Maharashtra')
city_hyd = state_ap.cities.create(name: 'Hyderabad')
state_ap.cities.create([{name: 'Tirupathi'}, {name: 'Visakhapatnam'}])
state_mh.cities.create([{name: 'Mumbai'}, {name: 'Pune'}, {name: 'Thane'}])
问题
当我试图找到“印”在所有城市使用
country_in.cities
我得到这个错误:当我试图找到哪个国家的城市“海德拉巴”是ActiveRecord::HasManyThroughAssociationNotFoundError: Could not find the association :state in model Country
,使用
city_hyd.country
,我得到nil
为什么CIT之间的联系国家和国家不在场?
我的关联错了吗还有其他我错过了吗?