无法正确定义活动记录关联

时间:2011-11-03 06:24:28

标签: ruby-on-rails activerecord associations

我有以下型号,

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

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

当我试图找到“Hyderabad”所在的国家/地区时,使用

ActiveRecord::HasManyThroughAssociationNotFoundError: Could not find the association :state in model Country,我得到 city_hyd.country

为什么城市和国家之间的联系不存在?

我的协会是否错了是否还有其他我错过的内容?

1 个答案:

答案 0 :(得分: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需要复数形式,而不是单数形式。
  • 如果您在belongs_to中使用City,则表格中需要定义state_id(这将是多余的)。所以我通过getter方法替换了它。无法使用相应的setter方法。

我希望现在适合你。