palkan/store_attribute

Storing Array Type Objects

Closed this issue · 1 comments

Is it possible to store an :array type?

The documentation says type A symbol such as :string or :integer, or a type object to be used for the accessor, but wondering if I can store arrays too. For example, something like this:

  store_attribute :details, :chapter_ids_stored, :array, default: []
  store_attribute :details, :chapter_ids_stored, :object, default: []

I'm currently storing relationship ids in Redis cache, since they are frequently used and costly to calculate. But wondering whether I could use store_attribute instead so store these ids in the actual record, then replace them upon updating the model.

I could store it as a :string converting to a comma separated list first, and then back again to an array, but would be nicer if it was possible to just store as an array. Is there a way to achieve this?

Ah-ha! I discovered I can use :json type looking at ActiveRecord::Type. This is perfect because now I can do the following:

store_attribute :details, :chapter_ids_stored, :json, default: []

This lets me store and retrieve arrays. 👍