0

[All codes here are samples] I have the Book model with the info field as hstore.

class Book < ActiveRecord::Base
  serialize :info, ActiveRecord::Coders::NestedHstore
end

and the info field is filled like this:

info: {"tags" => ["tag one", "tag two"]}

I need a query that I can find the books that contains the tag "tag one". How can I accomplish this?

2
  • Is this useful viget.com/extend/…? Commented Feb 18, 2016 at 18:58
  • No :( It is not using hstore like this. Commented Feb 18, 2016 at 19:02

1 Answer 1

1

You might not want to use a a hstore column here at all. Since hstore stores the values as plain text you need to do something like:

Book.where("WHERE info->'tags' LIKE '%?%'", "bestseller");

Seems like a decent idea until you realize that you are doing a full text search on a comma delimited string.

Instead you might want to use a tags table and a book_tags join table the good old way.

Sign up to request clarification or add additional context in comments.

7 Comments

Thanks. Yes, realizing that, seems like not a very good way. Are you aware of more optimized ways of doing such query? The book and tags were just examples, both the key and possible values are dynamic.
If my array can contain 'any', 'anyone' and I search for any, in this way I would get records that can have 'anyone' but not 'any'.
Not really, I think its more an issue of proper database design - hstore is great for key/value data but it does not automatically turn Postgres into Mongodb. If you are shoving serialized data into a hstore than you should most likely be using a relation instead.
"If my array can contain 'any', 'anyone' and I search for any, in this way I would get records that can have 'anyone' but not 'any'." - yeah that why its a really bad idea. You could use a regexp but its going to be even slower.
Or use a JSON column instead as it actually supports nested scalars.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.