我有一个像这样的当前城市和国家模型
# City model
city:string
country_code:string
# Country model
country:string
country_code:string
我正在尝试使用 country_code 作为 foreign_key 而不是使用默认的 country_id 在两个模型之间创建关联。
# city.rb
belongs_to :country, :foreign_key => "country_code"
# country.rb
set_primary_key :country_code
has_many :cities, :foreign_key => "country_code"
此查询不起作用
ruby-1.9.2-p290 :016 > Country.where(:country_code => "uy").cities
NoMethodError: Country Load (0.2ms) SELECT "countries".* FROM "countries" WHERE "countries"."country_code" = 'uy'
undefined method `cities' for #<ActiveRecord::Relation:0x007f8e92ca0df0>
from /Users/pel/.rvm/gems/ruby-1.9.2-p290/gems/activerecord- 3.2.3/lib/active_record/relation/delegation.rb:45:in `method_missing'
from (irb):16
from /Users/pel/.rvm/gems/ruby-1.9.2-p290/gems/railties-3.2.3/lib/rails/commands/console.rb:47:in `start'
from /Users/pel/.rvm/gems/ruby-1.9.2-p290/gems/railties-3.2.3/lib/rails/commands/console.rb:8:in `start'
from /Users/pel/.rvm/gems/ruby-1.9.2-p290/gems/railties- 3.2.3/lib/rails/commands.rb:41:in `<top (required)>'
from script/rails:6:in `require'
from script/rails:6:in `<main>'