Forum: Ruby on Rails 2 levels or more nested :joins w/ AR search conditions

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Shilo A. (Guest)
on 2009-02-23 18:43
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 :)
Frederick C. (Guest)
on 2009-02-23 19:20
(Received via mailing list)
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
Shilo A. (Guest)
on 2009-02-24 12:57
Works great - thanks.

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

http://www.spacevatican.org/2008/8/8/nested-includ...

http://blog.weberapps.com/?p=26
This topic is locked and can not be replied to.