Rails .where() 查询不起作用 [英] Rails .where() query not working

查看:65
本文介绍了Rails .where() 查询不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

非常感谢您的帮助.我有一个 locationsads 表.位置 has_many :ads我对位置模型执行以下查询.

Thanks a lot for your help. I have a locations and ads table. Location has_many :ads I perform the following query on Location Model.

@locations = Location.joins(:ads).where(@location_params.require(:location).permit(:id)).includes(:ads)

然后我想对 @locations 执行额外的查询并根据 :ads

Then I want to perform an additional query on @locations and filter it based on :ads

@locations = @locations.joins(:ads).where(ads: @ads_params.require(:ads).permit(:id)).includes(:ads)

此查询不起作用.它返回一个空对象.

This query does not work. It returns an empty object.

=> #<Location::ActiveRecord_Relation:0x1e29270>

这是参数:

  1. location_params

  1. location_params

@location_params.require(:location).permit(:id) 
<ActionController::Parameters {"id"=>1} permitted: true>

  • ads_params

  • ads_params

    @ads_params.require(:ads).permit(:id)
    <ActionController::Parameters {"id"=>1} permitted: true>
    

  • 不允许像这样给出特定的列输入:

    It is not permitted to give a specific column input like this:

    @locations = Location.joins(:ads).where(locations: {id: 1}, ads: {id: 1})
    

    我有 postgresql,我没想过使用 SQL,但我不确定.

    I have postgresql, I did not think about using SQL, but I am not sure.

    我正在使用 rails 控制台来执行此查询,以进行测试.

    I am using rails console to do this query, for testing.

    @location_params 
    => <ActionController::Parameters {"location"=><ActionController::Parameters {"id"=>1} permitted: false>} permitted: false>
    
    
    @location_params.require(:location).permit(:id)
    => <ActionController::Parameters {"id"=>1} permitted: true>
    
    @ads_params
    => <ActionController::Parameters {"ads"=><ActionController::Parameters {"id"=>1} permitted: false>} permitted: false>
    
    @ads_params.require(:ads).permit(:id)
    => <ActionController::Parameters {"id"=>1} permitted: true>
    

    推荐答案

    试试这个,

    ads_params = @ads_params.require(:ads).permit(:id).to_h
    location_params = @location_params.require(:location).permit(:id).to_h
    @locations = Location.joins(:ads).where(locations: location_params, ads: ads_params)
    

    希望有帮助!

    这篇关于Rails .where() 查询不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆