首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >ActiveRecord与country_code:string而不是country_id的关联

ActiveRecord与country_code:string而不是country_id的关联
EN

Stack Overflow用户
提问于 2012-04-24 04:17:59
回答 1查看 818关注 0票数 3

我有一个当前的城市和国家模型,就像这样

代码语言:javascript
复制
# City model
city:string
country_code:string

# Country model
country:string
country_code:string

我正在尝试使用country_code作为foreign_key来创建两个模型之间的关联,而不是使用默认的country_id。

代码语言:javascript
复制
# city.rb
belongs_to :country, :foreign_key => "country_code"

# country.rb
set_primary_key :country_code
has_many :cities, :foreign_key => "country_code"

此查询不起作用

代码语言:javascript
复制
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>'
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-04-24 04:33:47

试试这个:

代码语言:javascript
复制
Country.where(:country_code => "uy").collect(&:cities)

你缺少的东西:

检查此错误:

代码语言:javascript
复制
 undefined method `cities' for #<ActiveRecord::Relation:0x007f8e92ca0df0>

where条件返回一个对象数组。例如(考虑到在某些情况下存在1个id )

代码语言:javascript
复制
 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

所以

代码语言:javascript
复制
  Country.find(1) IS NOT EQUAL TO Country.where(:id=> 1)

代码语言:javascript
复制
 Country.find(1) IS EQUAL TO Country.where(:id=> 1).first

这就是基础知识。所以问题是

代码语言:javascript
复制
Country.where(:country_code => "uy") 

将返回一个数组,然后您尝试将"cities“映射应用于该数组,而该数组实际上并不存在。因此,您需要做的是“收集”,它将遍历该数组中的所有对象,然后找出每个"country“对象的城市,并返回数组的另一个数组。

还有一件事需要注意:

代码语言:javascript
复制
 Country.where(:country_code => "uy") 

将返回一个类似如下的数组:

代码语言:javascript
复制
['a','b','c','d']

代码语言:javascript
复制
Country.where(:country_code => "uy").collect(&:cities)

将返回如下数组:

代码语言:javascript
复制
  [[1,2,3,4],[2,3,6,8],[8],[10]] ie an array of an array.

所以你需要像这样把它展平:

代码语言:javascript
复制
  Country.where(:country_code => "uy").collect(&:cities).flatten

然后,如果您需要唯一的城市(如果需要,根据记录,我认为您在这种情况下不需要),可以将.uniq添加到数组中。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10287632

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档