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