【发布时间】:2016-06-14 18:10:56
【问题描述】:
我的产品模型有一个 jsonb 字段 specs(我们使用 ActiveRecord 的 store_accessor 进行管理)。我的许多产品规范在该哈希中都有一个名为 spec_options 的规范。
在此之前,spec_option 字段只是文本。现在它需要是一个数组。
之前用于查询该字段的产品的范围是这样的:
scope :with_spec_options, ->(spec_options) {
where("'#{spec_options}'::jsonb \? (specs->>'spec_option')")
}
Ruby 等价物(只是为了帮助理解这是在做什么):
select{ |product| spec_options.include?(product.specs['spec_option']) }
ActiveRecord 等效项(如果 spec_option 是常规列):
where(spec_option: spec_options)
但是,既然specs['spec_options'] 是一个数组,我就不能这样做了。我想我需要使用 postgres 的 ?| jsonb 运算符,但我不知道如何将此操作的右侧转换为正确的格式。
Ruby 等价物:
def self.with_spec_options(spec_options)
all.select{|product|
if product.specs['spec_options'].present?
product.specs['spec_options'].any?{|option|
spec_options.include?(option)
}
else
false
end
}
end
有人有想法吗?
【问题讨论】:
标签: ruby-on-rails postgresql activerecord jsonb