I have a search engine controller to have advanced search. Here is my controller.
@search = Building.joins('INNER JOIN "floors" ON "floors"."building_id" = "buildings"."id" INNER JOIN "spaces" ON "spaces".floor_id = "floors".id')
@building = []
@building << @search.where("buildings.name like ?", params[:building_name]) if params[:building_name]
@building << @search.where("Spaces.space_type_id = ?", params[:space_type][:space_type_id]) if params[:space_type][:space_type_id]
@building.flatten!
But, in my WEBrick shell, I see he only do the last where. I have data in params building_name and space_type.
I take this example for another Stack Overflow (I don't remember the link). But if I remove the second where, the building_name is taken.
What's wrong? Bad definition of my @building array?
I think what's happening here is that you're storing two ActiveRecord::Relation's, but rails isn't actually getting the results. As a result, your flatten isn't working as you expect.
QUESTION Are you trying to get all buildings where name is like building_name OR a space_type or is it building_name AND space_type. The solution below assumes the latter, please let me know if it's the former.
Could you try this:
@search = Building.joins('INNER JOIN "floors" ON "floors"."building_id" = "buildings"."id" INNER JOIN "spaces" ON "spaces".floor_id = "floors".id')
@search = @search.where("buildings.name like ?", params[:building_name]) if params[:building_name]
@search = @search.where("Spaces.space_type_id = ?", params[:space_type][:space_type_id]) if params[:space_type][:space_type_id]
@building = @search
This should scope your query according to each criteria but only return the values when you need them.