Rails - 查找hstore键不存在或= nil的所有记录

时间:2016-01-07 00:08:53

标签: ruby-on-rails activerecord hstore

如何找到hstore键不存在的类中的所有对象,或者如果存在,则不是nil?

产品表包含t.hstore "image_urls", default: {}

的hstore
image_urls

这将使所有没有为Product.where(image_urls: ['', nil]) 设置有用值的产品:

image_urls[:thumbnail]

但是,如果我想找到产品Product.where(image_urls[:thumbnail]: ['', nil]) 为零或不存在的所有产品怎么办?

这不起作用:

public class KafkaAvroReflectionSerializer extends KafkaAvroSerializer {
   private final EncoderFactory encoderFactory = EncoderFactory.get();

   @Override
   protected byte[] serializeImpl(String subject, Object object) throws SerializationException {
      //TODO: consider caching schemas
      Schema schema = null;

      if(object == null) {
         return null;
      } else {
         try {
            schema = ReflectData.get().getSchema(object.getClass());
            int e = this.schemaRegistry.register(subject, schema);
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            out.write(0);
            out.write(ByteBuffer.allocate(4).putInt(e).array());

            BinaryEncoder encoder = encoderFactory.directBinaryEncoder(out, null);
            DatumWriter<Object> writer = new ReflectDatumWriter<>(schema);
            writer.write(object, encoder);
            encoder.flush();
            out.close();

            byte[] bytes = out.toByteArray();
            return bytes;
         } catch (IOException ioe) {
            throw new SerializationException("Error serializing Avro message", ioe);
         } catch (RestClientException rce) {
            throw new SerializationException("Error registering Avro schema: " + schema, rce);
         } catch (RuntimeException re) {
            throw new SerializationException("Error serializing Avro message", re);
         }
      }
   }
}

1 个答案:

答案 0 :(得分:0)

我认为您正在寻找以下运营商:

hstore ? key     # does hstore contain key?
hstore @> hstore # does left hstore contain right?

所以最终的解决方案是:

Product.where("not image_urls ? 'thumbnail' or not image_urls @> 'thumbnail=>NULL'")