2011-11-03 25 views
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之间的联系国家和国家不在场?

我的关联错了吗还有其他我错过了吗?

回答

0

这里缺少的环节如下(见"Rails Guides for Associations"):

class Country < ActiveRecord::Base 
    has_many :states 
    has_many :cities, :through => :states 
end 

class City < ActiveRecord::Base 
    belongs_to :state 
    def country 
    state ? state.country : nil 
    end 
end 

我的变化是以下几点:

  • has_many :through需要的复数形式,而不是单数。
  • 如果您在City中使用belongs_to,则需要在表中定义一个state_id(这将是多余的)。所以我通过getter方法取代了它。相应的setter方法是不可能的。

我希望现在适合你。