Last active
March 20, 2017 19:39
-
-
Save g8d3/5d94e3c25d8908c6f4237f6e0a25b6a5 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
=begin | |
Given enum like status: %i(bad good great) | |
ransacker(:status){ Arel.sql(ites('status')) } | |
will allow to perform: | |
Model.search(status_cont: 'a') => returns models with bad and great statuses | |
Model.search(status_cont: 'g') => returns models with good and great statuses | |
Another way to solve http://stackoverflow.com/questions/37257835/searching-on-an-enum-field-with-ransack | |
=end | |
# This method is not needed | |
def self.enums_to_db | |
defined_enums.each do |name, map| | |
connection.execute <<~EOF | |
CREATE TYPE #{name} AS ENUM ('#{map.keys.join("', '")}'); | |
EOF | |
end | |
end | |
def self.hash_to_psql_case(field, hash, other = nil) | |
hash.reduce("CASE") do |m, kv| | |
k, v = kv | |
m += " WHEN #{field}=#{v} THEN '#{k}'" | |
end + | |
(other.present? ? " ELSE '#{other}'" : '') + | |
' END' | |
end | |
singleton_class.send(:alias_method, :htpc, :hash_to_psql_case) | |
def self.int_to_enum_string(field) | |
htpc(field, defined_enums[field]) | |
end | |
singleton_class.send(:alias_method, :ites, :int_to_enum_string) | |
# ransacker(:attempt_type){ Arel.sql(ites('attempt_type')) } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment