简体   繁体   中英

Ordering with Rails query with Hstore

I have a model Post

#<Post id: 121978, created_at: "2014-05-02 18:11:15", updated_at: "2014-05-02 18:11:15", data: {"hi"=>"1", "hello"=>"9999"}, review_id: nil> 

And I'd like to sort them based on hello within the hstore datatype column data

I made this query:

Post.order("data -> 'hello'")

Which works but since Hstore is in string, I have 780, 78, 77, ... as an output.

I think you can cast the value as an integer before being processed by order. I'm not that familiar with Hstore, but here are some examples of how you might try to do that:

Post.order("CAST(data -> 'hello' AS INT)")
Post.order("CONVERT(INT, data -> 'hello')")
Post.order("(data -> 'hello') * 1")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM