Skip to content

Instantly share code, notes, and snippets.

@ritec
Last active August 10, 2017 18:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ritec/cc96185b087c64f3ab40ea3a5625bb34 to your computer and use it in GitHub Desktop.
Save ritec/cc96185b087c64f3ab40ea3a5625bb34 to your computer and use it in GitHub Desktop.
Useful and Common Ruby Operations and Tricks
Arrays
# http://stackoverflow.com/questions/7857019/rails-remove-element-from-array-of-hashes
filtered_array = array.reject { |h| blacklist.include? h['email'] }
filtered_array = array.select { |h| !blacklist.include? h['email'] }
# Hstore Tips and Tricks
# Sort based on the Hstore data:
2.1.1 :022 > Post.order("data->'hello' DESC")
=> #<ActiveRecord::Relation [#<Post id: 4, created_at: "2014-04-16 01:05:49", updated_at: "2014-04-16 01:05:49", data: {"hi"=>"23", "hello"=>"22"}>, #<Post id: 3, created_at: "2014-04-16 01:05:37", updated_at: "2014-04-16 01:05:37", data: {"hi"=>"13", "hello"=>"21"}>, #<Post id: 2, created_at: "2014-04-16 01:05:28", updated_at: "2014-04-16 01:05:28", data: {"hi"=>"3", "hello"=>"2"}>, #<Post id: 1, created_at: "2014-04-16 01:05:05", updated_at: "2014-04-16 01:05:05", data: {"hi"=>"2", "hello"=>"1"}>]>
# Where inside a JSON object:
Record.where("data ->> 'likelihood' = '0.89'")
# Searching nested json object:
2.1.1 :130 > r.column_data
=> {"data1"=>[1, 2, 3], "data2"=>"data2-3", "array"=>[{"hello"=>1}, {"hi"=>2}], "nest"=>{"nest1"=>"yes"}}
2.1.1 :130 > Record.where("column_data -> 'nest' ->> 'nest1' = 'yes' ")
# Searching within array:
Record.where("column_data #>> '{data1,1}' = '2' ")
# Searching within a value that’s an array:
Record.where("column_data #> '{array,0}' ->> 'hello' = '1' ")
# this only find for one element of the array.
# All elements:
Record.where("column_data ->> 'array' LIKE '%hello%' ")
# This is advised against in rails, use below:
Record.where("column_data ->> 'array' LIKE ?", "%hello%")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment