Is it possible to create an attribute for a class that is an array? I tried reading this but I didn\'t get much out of it. I want to do something like this:
clas
Rails 6+
In Rails 6 (and to a lesser degree Rails 5) you can use the Attribute API which will allow you to create a typed, "virtual"/non-db backed column and even a default attribute. For example:
attribute :categories, :jsonb, array: true, default: [{ foo: 'bar' }, { fizz: 'buzz' }]
Which results in:
Example.new
# {
"id" => nil,
"created_at" => nil,
"updated_at" => nil,
"categories" => [
[0] {
"foo" => "bar"
},
[1] {
"fizz" => "buzz"
}
]
}
Note that you can use any type, but if it's not already available, you'll have to register it. In the above case, I use PostgeSQL
as the database and which has already registered :jsonb
as a type.