Skip to content

Instantly share code, notes, and snippets.

@goodfeel
Last active August 29, 2015 14:06
Show Gist options
  • Save goodfeel/944203c64cb659bb3ad3 to your computer and use it in GitHub Desktop.
Save goodfeel/944203c64cb659bb3ad3 to your computer and use it in GitHub Desktop.
Ransack Note
# hstore customized, in the model.
# given your h store field is 'data' and the hash key named 'trace'
ransacker :trace do |parent|
Arel::Nodes::InfixOperation.new('->', parent.table[:data], 'trace')
end
# Filter some field out when query field selection for ransack from (Still put in your model)
def self.ransackable_attributes(auth_object = nil)
super - ['id', 'player', 'updated_at']
end
## Dynamic ransacker ;)
# put this in concerns folder and setup
# SEARCHABLE_HSTORE_FIELDS = ['hstore_field1', 'hstore_field2'] before include RansackHstore
module RansackHstore
extend ActiveSupport::Concern
included do
if self::SEARCHABLE_HSTORE_FIELDS
self::SEARCHABLE_HSTORE_FIELDS.each do |s|
fields = ActiveRecord::Base.connection.execute("SELECT key, count(*) FROM (SELECT (each(#{s})).key FROM #{self.table_name}) AS stat GROUP BY key ORDER BY count DESC, key;")
fields.each do |e|
ransacker "#{e['key'].to_sym}" do |parent|
Arel::Nodes::InfixOperation.new('->', parent.table[s.to_sym], e['key'])
end
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment