I have a current City and Country model like this
# City model
city:string
country_code:string
# Country model
country:string
country_code:string
I’m trying to create an association between both models using the country_code as foreign_key instead of using default’s 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 query is not working
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>'
Try this:
What you are missing:
Check this error:
where condition returns an array of objects. For example (Considering 1 id is present, in some cases)
So
But
Thats about the basics. So the issue was
will return an array and then you are trying to apply “cities” mapping to that array which really don’t exists. So what you need to do is “collect” that will loop over all the objects in that array and then find out cities for each of these “country” objects and return an another array of array.
One more thing to notice:
will return an array something like this:
but
will return an array like:
So you need to flatten it like this:
Then if you need to need unique cities(if needed, based upon the records, which i don’t think you need for this case), you can add .uniq to the array.