首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么我对jsonb的rails范围查询不能工作?

为什么我对jsonb的rails范围查询不能工作?
EN

Stack Overflow用户
提问于 2018-10-12 07:56:10
回答 1查看 282关注 0票数 0

我有一个带有默认{}的jsonb列,添加了键"home_page":"1" (update_attribute和save.)。

我在模型上增加了一个范围-

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

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

帮助:(

rails - 5.2.2,ruby-2.5,db - PostgreSQL 10.3

EN

回答 1

Stack Overflow用户

发布于 2018-10-12 13:58:27

您的范围正在运行

代码语言:javascript
复制
class Thing < ApplicationRecord
  scope :home_page, -> { where("my_column ->> 'home_page' = ?", "1") }
end

正如这个通过的规范所示:

代码语言:javascript
复制
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!来查看是否存在任何验证错误。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52774863

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档