Ruby-on-rails – Rails ‘includes’ and ‘where’ with belongs_to association

activerecordruby-on-railsruby-on-rails-3

I have 2 models: PassportVisa and Country.

Country Model

class Country < ActiveRecord::Base
  attr_accessible :iso, :name
  has_many :passport_visa, foreign_key: :country_id
end

PassportVisa Model

class PassportVisa < ActiveRecord::Base
  belongs_to :country, foreign_key: :country_id
end

And I'm trying to query the passportvisa model like that:

@passport_visa_supplement_o   = PassportVisa.includes(:assets).where(:visa_type => 'Official' ,:assets => {:pdf_type => 'supplement'}).order("country ASC")

But it says that:

PG::Error: ERROR: column "country" does not exist

It's because on my PassportVisa table I only have access to the country_id. Using that same query (with a few adjustments) How can I automatically get the country name?

The :assets is from another model that I'm using for upload, it should stay there.

Best Solution

you are not including the country table in your joins.

if you want to order for country name you can just do

@passport_visa_supplement_o = PassportVisa.includes([:assets, :country]).uniq.where(:visa_type => 'Official' ,:assets => {:pdf_type => 'supplement'}).order("countries.name ASC")

I added the .uniq because with the outer join you could have duplicates

Related Question