2 levels or more nested :joins w/ AR search conditions

Sorry for the ambiguous title, but here’s the problem:

Say I have tables of cities, districts and countries such that:

city belongs_to district (district has_many cities)
district belongs_to country (country has_many districts)

Therefore, while looping through a city I can easily access the
country’s name via city.district.country.name, and I don’t have to
include country_id in the city model.

I want to add a search to the city view to sort by country name. Doing
it by district is simple using the :joins flag:

City.find(:all, :joins => [:district],
:conditions => [“districts.name LIKE ?”, “%#{search_text}%”])

This only goes one level deep. My question is - how can I search the
country name through the city model? If I try the same notion as above,
it won’t work:

City.find(:all, :joins => [:country],
:conditions => [“countries.name LIKE ?”, “%#{search_text}%”])

Gives the error:
ActiveRecord::ConfigurationError: Association named ‘country’ was not
found; perhaps you misspelled it?

Anyone had any luck with such a thing? And what if country was linked to
another model I’d like to view through city (say, planet) - is there
some generic solution to access several levels through the calling
models?

I’m not going to go 20 levels down, but 2-3 sounds fair :slight_smile:

On 23 Feb 2009, at 16:43, Shilo A. wrote:

Gives the error:
ActiveRecord::ConfigurationError: Association named ‘country’ was not
found; perhaps you misspelled it?

Anyone had any luck with such a thing? And what if country was
linked to
another model I’d like to view through city (say, planet) - is there
some generic solution to access several levels through the calling
models?

Try the 3rd google hit for rails nested joins

Fred

Works great - thanks.

Here are top two links for those of you who are lazy typers:

http://blog.weberapps.com/?p=26