ActiveRecord association with country_code: string instead of country_id

I have a current City and Country model similar to this

# City model
city:string
country_code:string

# Country model
country:string
country_code:string

I am trying to create a relationship between both models using country_code as foreign_key, instead of using 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"

This request does not work

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>'
+3
source share
1 answer

Try the following:

Country.where(:country_code => "uy").collect(&:cities)

What you are missing:

Check out this error:

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

where the condition returns an array of objects. For example (in some cases 1 id is present)

 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

So,

  Country.find(1) IS NOT EQUAL TO Country.where(:id=> 1)

But

 Country.find(1) IS EQUAL TO Country.where(:id=> 1).first

Here are the basics. So the problem was

Country.where(:country_code => "uy") 

, "" , . , , "", , "" .

:

 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 .

+3

All Articles