私はこのような現在の都市と国のモデルを持っています
# City model
city:string
country_code:string
# Country model
country:string
country_code:string
デフォルトのcountry_idを使用する代わりに、country_codeをforeign_keyとして使用して、両方のモデル間の関連付けを作成しようとしています。
# 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>'