Summary
Thanks a lot for your help.
I have a locations
and ads
table. Location has_many :ads
I would like to make a query of Location
Model with a join
with Ad
Model, to filter entries on parameters of Location
and Ad
.
@locations = Location.joins(:ads).where(locations: location_params, ads: location_params[:ads_attributes])
This is the location_params method (empty fields will be deleted with another method that is working fine).
params.require(:location).permit(:country, {:ads_attributes => [:remote, :days]})
This is an example of my query. I have a method which remove empty fields from location_params. It works fine.
SELECT "locations".* FROM "locations" INNER JOIN "ads"
ON "ads"."location_id" = "locations"."id"
WHERE "ads_attributes"."remote" = $1 [["remote", "1"]]
In this case location_params has the following fields:
<ActionController::Parameters {"ads_attributes"=>
<ActionController::Parameters {"remote"=>"1"} permitted: true>} permitted: true>
This is the result, an empty object even if I have entries with those parameters in my table
#<Location::ActiveRecord_Relation:0x3fb83def8190>
Update
- First Issue - Solved from Péter Tóth
Solution. Using .includes(:ads)
for not re-executing the query with @locations[0].ads
.
@locations = Location.joins(:ads).where(locations: {id: 1}, ads: {id: 1})
The problem is, when i select from location the ads
, it will perform again the query and delete the previous filter ads.id = 1.
@locations[0].ads
The result is not only ad with id=1 will be selected but all ads of that @location[0] will be selected.
- Second Issue
I am able to execute the query:
@locations = Location.joins(:ads).where(locations: {id: 1}, ads: {id: 1})
Or
@locations = Location.joins(:ads).where(location_params)
But not
@locations = Location.joins(:ads).where(locations: location_params, ads: ads_params)
But this can be solved as follows: Perform a first query on Location
@locations = Location.joins(:ads).where(@location_params.require(:location).permit(:id)).includes(:ads)
which returns all locations with those parameters, then I need to filter @locations based on the ads filters. The problem is that I am not able to do the following query.
@locations = @locations.joins(:ads).where(ads: @ads_params.require(:ads).permit(:id)).includes(:ads)
{ country: location_params[:country] }
. There are several fields and there is a method which delete them if they are empty. Iflocation_params[:country]
is blank then it will be deleted and it will benil
. I would like to just inputlocation_params
to the query without giving a specific column to be selected. Do you know how to fix the following query so that it will work?@locations = Location.joins(:ads).where(locations: new_params, ads: new_params[:ads_attributes])
Thanks – Commitment