madeintandem / hstore_accessor

Adds typed hstore-backed field support to ActiveRecord models.
MIT License
242 stars 47 forks source link

Support multiple hstore columns in same model #67

Closed marcusg closed 9 years ago

marcusg commented 9 years ago

When you have multiple hstore columns for one model it is not possible to use hstore_accessor, because no prefix/scope can be set or did I miss something?

I use the following config in my model.

class MyModel < AR::Base

    hstore_accessor :hstore_1, my_key: :integer
    hstore_accessor :hstore_2, my_key: :integer

end

The last hstore_accessor call overwrites the first one, which seems reasonable. It would be nice if one can set a prefix which results in different query methods instead of MyModel.my_key. What about this one?

MyModel.hstore_1_my_key
MyModel.hstore_2_my_key
crismali commented 9 years ago

@marcusg you haven't missed anything. There is currently no way to add prefix to the generated method names in the gem.

It's unlikely that HstoreAccessor this sort of functionality in future, but you could do something like this to namespace the keys:

  hstore_accessor :hstore_1, my_key: :integer
  %w(my_key my_key= my_key? my_key_changed? my_key_was my_key_change reset_my_key! restore_my_key! my_key_will_change!).each do |method_name|
    alias_method "hstore_1_#{method_name}", method_name
  end
crismali commented 9 years ago

Additionally, you could specify that the store keys are the same and name just that field something different:

hstore_accessor :options,  options_color: { data_type: :string, store_key: "c" }

hstore_accessor :data,  data_color: { data_type: :string, store_key: "c" }
marcusg commented 9 years ago

@crismali thanks, using the options hash with data_type and store_key helped me.