Created
May 15, 2013 19:13
-
-
Save andreypronin/5586511 to your computer and use it in GitHub Desktop.
HStore accessor: Postgres, Rails
This file contains 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
def hstore_get(field_name) | |
method(field_name).call | |
end | |
def hstore_set(field_name,value) | |
method("#{field_name}=").call(value) | |
end | |
def hstore_accessor(field_name,name) | |
define_method(name) do | |
hstore = hstore_get(field_name) | |
hstore && hstore[name] | |
end | |
define_method("#{name}=") do |value| | |
hstore = hstore_get(field_name) || {} | |
hstore_set field_name, hstore.merge( name => value ) | |
end | |
define_method("#{name}_present?") do | |
hstore = hstore_get(field_name) | |
hstore && hstore.has_key?(name) | |
end | |
end |
This file contains 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
class CreateXxx < ActiveRecord::Migration | |
def change | |
create_table :xxxs do |t| | |
t.hstore :params | |
end | |
add_index "xxxs", ["params"], name: "xxxs_gin_params", using: :gin | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment