ActiveRecord scope with association

rails 3.2.11

I have models

Airport
:name, :string
belongs_to city
City
:name, :string
has_many airports
belongs_to country
Country
:name, :string
has_many cities

and I want to search a particular airport through this association

scope :search_airport, where(:name => name, :city => city, :country =>
country)

clearly this does not work

Could anyone show me how to set up a scope through association?

the input maybe only airport name, or airport name with city, or airport
name with city and country name.

soichi

On 3 February 2013 02:16, Soichi I. [email protected] wrote:

belongs_to country
Country
:name, :string
has_many cities

and I want to search a particular airport through this association

What do you mean by search an airport? Do you mean you want to find
the airport with the given name, city, country?

scope :search_airport, where(:name => name, :city => city, :country =>
country)

clearly this does not work

Could anyone show me how to set up a scope through association?

the input maybe only airport name, or airport name with city, or airport
name with city and country name.

If it is the particular airport that you are trying to find then if
you have the airport name (which you suggest you have in all cases
shown) then there is only one airport that it can be, the city and
country are irrelevant (assuming that airport name is unique).
Therefore you just need
where :name => airport_name

Colin

Thanks for your reply.

The thing is users may or may not know (or remember) the name of the
airport they are looking for.
So the search method needs to narrow down airports from the user inputs
including city names and/or country names.

For example, you wish to travel from JFK New York USA (though it’s a
famous airport…), you don’t clearly remember the name of the airport.
All you can pull out from your memory is the country and the city, in
this case ‘New York’ and ‘USA’

You enter ‘New York USA’ in the form, the app narrows down the
possibilities to the airport in ‘New York (State) USA’. Once the list
of possible airports is small, you now may be able to choose the name of
the airport relatively easily.

I hope make myself clearer.

I am looking for something like

scope :search_by_name, lambda { |name, city, country|
    joins(:name).where("LOWER(name) LIKE ? AND LOWER(city) LIKE ? 

AND LOWER(country) LIKE ?", “%#{params[:name].downcase}%”)
}

I have made this up, surely it won’t work :slight_smile:

Thanks for your help.

I would like to raise another question related to this but different in
a new thread.

soichi