【问题标题】:Rails .where() query not workingRails .where() 查询不起作用
【发布时间】:2017-08-03 06:56:11
【问题描述】:

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

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

然后我想对@locations 执行一个额外的查询并根据:ads 过滤它

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

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

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

这是参数:

  1. 位置参数

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

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

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

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

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

查询参数

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

@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>

【问题讨论】:

  • 你能把你在服务器日志中看到的整个参数哈希写在这里
  • 只需添加binding.pry,然后在控制台中运行@locations.joins(:ads).where(ads: ads_params).first,就会看到无效的PG语句错误,你必须修复它。
  • @AndreyDeineko @RSB 我根据您的要求更新了我的帖子。我正在控制台中进行测试,我使用.first 运行代码并收到TypeError: cant't quote ActionController::Parameters
  • 伙计们,SO 的主要目标是提供帮助,因为给出的答案有效,我说接受它,我们很高兴我们帮助了 :)始终添加环境设置信息(Ruby 版本、Rails 版本等 :))
  • 非常感谢 Andrey 和 RSB。我接受你的回答 RSB。

标签: sql ruby-on-rails ruby postgresql ruby-on-rails-5


【解决方案1】:

试试这个,

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)

希望有帮助!

【讨论】:

    猜你喜欢
    • 2016-04-17
    • 2015-03-10
    • 1970-01-01
    • 2012-03-21
    • 2017-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多