概述
非常感谢您的帮助。
我有一个名为locations
和ads
的表格。位置has_many:ads
我想要使用Location
模型的join
与Ad
模型进行查询,以根据Location
和Ad
的参数过滤条目。
@locations = Location.joins(:ads).where(locations: location_params, ads: location_params[:ads_attributes])
这是location_params方法(空字段将使用另一个正常工作的方法删除)。
params.require(:location).permit(:country, {:ads_attributes => [:remote, :days]})
这是我的一个查询示例。我有一个方法可以从location_params中删除空字段,它运行良好。
SELECT "locations".* FROM "locations" INNER JOIN "ads"
ON "ads"."location_id" = "locations"."id"
WHERE "ads_attributes"."remote" = $1 [["remote", "1"]]
在此情况下,location_params 具有以下字段:
<ActionController::Parameters {"ads_attributes"=>
<ActionController::Parameters {"remote"=>"1"} permitted: true>} permitted: true>
这是结果,在我的表中即使有符合这些参数的条目,也是一个空对象。
#<Location::ActiveRecord_Relation:0x3fb83def8190>
更新
- 第一个问题 - 来自Péter Tóth
解决方案。使用.includes(:ads)
来避免重新执行查询@locations[0].ads
。
@locations = Location.joins(:ads).where(locations: {id: 1}, ads: {id: 1})
问题是,当我从位置选择
ads
时,它会再次执行查询并删除先前的过滤器ads.id = 1
。@locations[0].ads
这个结果不仅会选择id=1的广告,还会选择所有@location[0]的广告。
- 第二个问题
我能够执行这个查询:
@locations = Location.joins(:ads).where(locations: {id: 1}, ads: {id: 1})
或者
@locations = Location.joins(:ads).where(location_params)
但不是
@locations = Location.joins(:ads).where(locations: location_params, ads: ads_params)
但这可以通过以下方法解决: 在位置上执行第一次查询。
@locations = Location.joins(:ads).where(@location_params.require(:location).permit(:id)).includes(:ads)
这段代码返回所有符合参数要求的位置,然后我需要根据广告过滤器来筛选@locations。但问题在于我无法执行以下查询。
@locations = @locations.joins(:ads).where(ads: @ads_params.require(:ads).permit(:id)).includes(:ads)
@locations = Location.joins(:ads).where(locations: new_params, ads: new_params[:ads_attributes])
谢谢。 - Fabrizio Bertoglio<ActionController :: Parameters {"country"=>"IT", "location"=>"Leizpig"} permitted: true>
,而这是ads_params<ActionController :: Parameters {"remote"=>"1"} permitted: true>
,查询为空#<Location::ActiveRecord_Relation:0x3f9eeac68e00>
。 - Fabrizio Bertoglio