jsonb_accessor icon indicating copy to clipboard operation
jsonb_accessor copied to clipboard

Method for Enumerating Accessor Fields

Open joshuamcginnis opened this issue 6 years ago • 2 comments

I'm looking for a list that enumerates the defined accessors on a jsonb column, not unlike model_klass.new.attributes.keys which returns all attributes for a model (jsonb accessors included).

Digging through the source, I found that the lib is creating a helper method that does almost exactly what I need via klass.jsonb_store_key_mapping_for_credit_attributes?

Is it safe to use this method in production? Would it be useful to expose a more user-friendly and tested public api for enumerating the defined accessors?

In my use-case, I'm creating a lot of records using these accessors and for this task, my database returns the exact same accessor names as the ones I've defined in my model. With this helper method, I can simply loop through all the fields to do value assignment, as opposed to having to explicitly set each field ala .new(a: result[:a], b: result[:b], ...).

Thanks.

joshuamcginnis avatar Oct 01 '18 19:10 joshuamcginnis

I have this need too. I'd like to dynamically generate an admin interface based on the jsonb_fields.

I can get by with using jsonb_store_key_mapping_for_#{name}, but it'd be nice if there was a version with contained the field name and the type.

This is a public method, so I guess it appears to be OK to use it. There is a spec for it

This may meet my needs (not tested) yet.

jsonb_attributes_method_name = "jsonb_attributes_for_#{jsonb_attribute}"
# Defines methods on the model class
class_methods = Module.new do
  # Allows us to get a mapping of field names to store keys scoped to the column
  define_method(jsonb_attributes_method_name) do
    superclass_mapping = superclass.try(jsonb_attributes_method_name) || {}
    superclass_mapping.merge(field_types)
  end
end

rickychilcott avatar Jan 04 '19 15:01 rickychilcott

This brings up a good question, is anyone maintaining this?

rickychilcott avatar Jan 04 '19 15:01 rickychilcott

Closing for inactivity.

haffla avatar Dec 06 '23 17:12 haffla