I’m trying to create basic search in my web app. Here’s code of search function.
def self.search(title, category_id, city_id)
if title || category_id || city_id
joins(:category).where('title LIKE (?) AND category.category_id IN (?) AND city.city_id IN (?)', "%#{title}%", "%#{category_id}%", "%#{city_id}%")
else
scoped
end
end
I have these associations in my model:
has_one :category
has_one :city
And I get this error
ActionView::Template::Error (PG::Error: ERROR: missing FROM-clause entry for ta
ble "category"
LINE 1: ..._id" = "events"."id" WHERE (title LIKE ('%%') AND category.c...
I’m using PostgreSQL. What I can do to remove this error?
The form of
joinsthat you’re using wants the association name, the SQL wants the table name. The table should be calledcategories.A few other things:
:cityanywhere so your next error will be “Missing FROM-clause entry for table “city”. The solution will be to.joins(:city)and usecitiesin thewhere. But keep reading anyway.title LIKE ?is fine.=and a single value for the placeholder.categoriestable probably doesn’t have acategory_idcolumn, similarly for thecitiestable andcity_idcolumn. Those two columns should be in your model’s table.That looks like a lot of problems but they can be fixed without too much effort:
and you don’t even need
joinsor explicit table names at all.