我有一个当前的城市和国家模型,就像这样
# 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>'发布于 2012-04-24 04:33:47
试试这个:
Country.where(:country_code => "uy").collect(&:cities)你缺少的东西:
检查此错误:
undefined method `cities' for #<ActiveRecord::Relation:0x007f8e92ca0df0>where条件返回一个对象数组。例如(考虑到在某些情况下存在1个id )
Country.first // will return an object or nil
Country.find(1) // will return an object or will throw an exception
Country.where(:id=> 1) // will return an array of only one object with id 1所以
Country.find(1) IS NOT EQUAL TO Country.where(:id=> 1)但
Country.find(1) IS EQUAL TO Country.where(:id=> 1).first这就是基础知识。所以问题是
Country.where(:country_code => "uy") 将返回一个数组,然后您尝试将"cities“映射应用于该数组,而该数组实际上并不存在。因此,您需要做的是“收集”,它将遍历该数组中的所有对象,然后找出每个"country“对象的城市,并返回数组的另一个数组。
还有一件事需要注意:
Country.where(:country_code => "uy") 将返回一个类似如下的数组:
['a','b','c','d']但
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然后,如果您需要唯一的城市(如果需要,根据记录,我认为您在这种情况下不需要),可以将.uniq添加到数组中。
https://stackoverflow.com/questions/10287632
复制相似问题