jsonb_accessor
jsonb_accessor copied to clipboard
Method for Enumerating Accessor Fields
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.
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
This brings up a good question, is anyone maintaining this?
Closing for inactivity.