【问题标题】:why is my rails scope query on jsonb not working?为什么我对 jsonb 的 rails 范围查询不起作用?
【发布时间】:2019-03-17 09:50:09
【问题描述】:

我有一个带有默认 {} 的 jsonb 列,添加了密钥 "home_page":"1"(更新属性并保存...)。

我为模型添加了一个范围 -

scope :home_page, -> { where("my_column ->> 'home_page' = ?", "1") }

无论我做什么,我总是得到一个空的结果。

帮助:(

导轨 - 5.2.2, 红宝石 - 2.5, 数据库 - PostgreSQL 10.3

【问题讨论】:

  • 您确定您确实使用t.jsonb :my_column, default: -> { "'{}'::jsonb" } 正确设置了默认值吗?而且您没有以其他方式弄乱示例吗?我尝试复制该问题,并且得到了预期的结果。
  • add_column :my_table, :my_column, :jsonb, default: {} - 错了吗?
  • 不正确。
  • 所以这里的 wtf 错了?!?!拿不到...

标签: ruby-on-rails json postgresql jsonb


【解决方案1】:

您的示波器正在工作

class Thing < ApplicationRecord
  scope :home_page, -> { where("my_column ->> 'home_page' = ?", "1") }
end

如此通过规范所示:

require 'rails_helper'

RSpec.describe Thing, type: :model do
  after(:each) { Thing.destroy_all }
  describe '.home_page' do
    it "includes records with home_page: 1" do
      thing = Thing.create(my_column: { home_page: 1 })
      expect(Thing.home_page).to include thing
    end

    it "includes records with home_page: '1'" do
      thing = Thing.create(my_column: { home_page: '1' })
      expect(Thing.home_page).to include thing
    end

    it "does not return records that do not match the criteria" do
      Thing.create(my_column: { home_page: 0 })
      Thing.create(my_column: { xhome_page: 1 })
      expect(Thing.home_page).to be_empty
    end
  end
end

错误在于您的测试方法或设置。例如,您可以尝试拨打.save! 来查看是否有任何验证错误。

【讨论】:

  • 嗨,范围确实有效,问题是它总是返回一个空结果。
  • 那么你没有任何匹配范围的记录
猜你喜欢
  • 2023-03-15
  • 1970-01-01
  • 2013-06-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多