Ruby on rails ActiveRecord与国家/地区代码的关联:字符串而不是国家/地区id

Ruby on rails ActiveRecord与国家/地区代码的关联:字符串而不是国家/地区id,ruby-on-rails,ruby,ruby-on-rails-3,activerecord,Ruby On Rails,Ruby,Ruby On Rails 3,Activerecord,我现在有这样一个城市和乡村模型 # City model city:string country_code:string # Country model country:string country_code:string 我正在尝试使用country_代码作为外键,而不是使用default的country_id,在两个模型之间创建关联 # city.rb belongs_to :country, :foreign_key => "country_code" # country.rb

我现在有这样一个城市和乡村模型

# City model
city:string
country_code:string

# Country model
country:string
country_code:string
我正在尝试使用country_代码作为外键,而不是使用default的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>'
试试这个:

Country.where(:country_code => "uy").collect(&:cities)
您缺少什么:

检查此错误:

 undefined method `cities' for #<ActiveRecord::Relation:0x007f8e92ca0df0>
所以

但是

这是最基本的。所以问题是

Country.where(:country_code => "uy") 
将返回一个数组,然后您尝试将城市映射应用到该数组,而该数组实际上不存在。因此,您需要做的是收集将在该数组中的所有对象上循环的数据,然后找出每个国家/地区对象的城市,并返回另一个数组

还有一件事需要注意:

将返回类似以下内容的数组:

['a','b','c','d']
  Country.where(:country_code => "uy").collect(&:cities).flatten
但是

将返回如下数组:

  [[1,2,3,4],[2,3,6,8],[8],[10]] ie an array of an array.
所以你需要像这样把它展平:

['a','b','c','d']
  Country.where(:country_code => "uy").collect(&:cities).flatten

然后,如果您需要唯一的citiesif need,根据记录(我认为您在本例中不需要这些记录),您可以将.uniq添加到数组中。

到底是什么不起作用?你看到了什么行为?你有堆栈跟踪吗?“它坏了”绝对不是一个有效的错误描述。@Martin检查我的答案。我认为这会奏效,解释了很多事情。Country.where:Country\u code=>uy.first.cities也会奏效。@MarlinPierce我不否认这不会奏效。但从他试图引发的质疑来看,他似乎在一系列国家寻找城市。~MohitJain,你说得对。我一直在看他在顶部的字段描述,并将结果向后推。你说得对,我应该检查一下城市和国家的语义,并一直关注他的归属
Country.where(:country_code => "uy").collect(&:cities)
  [[1,2,3,4],[2,3,6,8],[8],[10]] ie an array of an array.
  Country.where(:country_code => "uy").collect(&:cities).flatten