Indrajeet
Indrajeet

Reputation: 23

Rails query associations for multiple tables

Iam developing a rails app in which I have two tables 'cities' and 'states'. From a search-box I send a phrase to be fetched from cities or states.
The text in the search box can be like 'Illinois' or 'Chicago' but thhe query should be in such a way that it looks into both cities and states table to check if the parameter given is found in either of the table or not.
What should be the query for this in rails??
I am fairly new to rails, so, not so good at queries yet.

Upvotes: 0

Views: 156

Answers (1)

thorsten müller
thorsten müller

Reputation: 5651

In this case you can't do much better than running the query independently against both tables:

@cities = City.where(name: params[:search])
@states = State.where(name: params[:search])

assuming the column is name

or if you want to allow for a more flexible search:

@cities = City.where("name LIKE '?%'", params[:search])
@states = State.where("name LIKE '?%'", params[:search])

Upvotes: 1

Related Questions