我有一个默认值为{}的 jsonb 列,并添加了密钥"home_page":"1"
(update_attribute并保存...)。
我为模型添加了范围-
scope :home_page, -> { where("my_column ->> 'home_page' = ?", "1") }
无论我做什么,我总是得到空洞的结果。
帮助:(
导轨-5.2.2, 红宝石-2.5, 数据库-PostgreSQL 10.3
答案 0 :(得分:0)
您的范围正在工作。
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!
来查看是否存在任何验证错误。