Rafael Fragoso
Rafael Fragoso

Reputation: 1309

Rails 'includes' and 'where' with belongs_to association

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.

Upvotes: 1

Views: 12042

Answers (1)

Vecchia Spugna
Vecchia Spugna

Reputation: 682

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

Upvotes: 2

Related Questions