Topic: classified ads in selected city and category, habtm...

I have classified ads (cads) related with cities and categories:

cad.rb
class Cad < ActiveRecord::Base
  has_and_belongs_to_many :categories
  has_and_belongs_to_many :cities
end

category.rb
class Category < ActiveRecord::Base
  has_and_belongs_to_many :cads
end

city.rb
class City < ActiveRecord::Base
    has_and_belongs_to_many :cads
end

First, i choose city (assume it's X) and receive classified ads associated with X and categories of these ads:
cities_controller.rb
    def show
        @city = City.find(params[:id])
        @cads = @city.cads
        @categories_inside_city = @city.find_categories_for_cads_in_selected_city
    end

city.rb
    def find_categories_for_cads_in_selected_city
    cads.map{|cad| cad.categories}.flatten.uniq
  end

After that i choose category (assume it's Y) and want to receive only
these classified ads which cities include X and categories include Y.

I can't figure out how to achieve this?

Re: classified ads in selected city and category, habtm...

Is this what you want?

@cads = Cad.find(:all, :include => [:categories, :cities], :conditions => ['categories.id = ? AND cities.id = ?', params[:category_id], params[:city_id]])

Railscasts - Free Ruby on Rails Screencasts

Re: classified ads in selected city and category, habtm...

I think this can be the solution, but i can't get it work, mayby i put it in wrong place.

I try to explain more details.

First i navigate to cities listing (localhost/cities/) and then i choose city ( /cities/show/1 ).
With "show" method in cities_controller i get classified ads that relates to this city and i get categories of these ads:

@city = City.find(params[:id])
@cads = @city.cads
@categories_inside_city = @cads.map{|cad| cad.categories}.flatten.uniq

In show.rhtml i create links to categories of classified ads of chosen city:
[...]
<% @categories_inside_city.each do |category| %>
    <%= link_to category.name,
                    :controller => "categories",
                    :action => "show",
                    :id => category
  %>
<% end %>
[...]

And then i click on one of these links (assume i click on "Health"). How i will get ads in "Health" category, but
only these in previously chosen city?