How to pluck hstore key with ActiveRecord

630 Views Asked by At

I have table with hstore column named name_translations with lots of translations:

{ 'en' => 'En name', 'es' => 'Es name', ... }

Its also serialized in model store_accessor :name_translations

I need to get id and ru key in name_translations hstore. I tried Model.select("id, name_translations -> 'ru'") and here is a query AR generates Model Load (0.6ms) SELECT id, name_translations -> 'ru' FROM "models" but output has only ids:

[#<Model id: 95>,
 #<Model id: 101>,
...

Currently I stopped on a bit ugly code:

Model.pluck(:id, :name_translations).map { |id, name| [id, name['ru']] }

Whats a way to make it better?

1

There are 1 best solutions below

1
On BEST ANSWER

You can use as in the select query, for example:

=> result = Model.select("id, name_translations -> 'ru' as something")
=> result.first.something

but output has only ids:

[#<Model id: 95>, #<Model id: 101>, ...

This is how AR works, if you're using dynamic attributes it's never showed in the output because it's not a real column it's an alias.