Array Attribute for Ruby Model

前端 未结 5 2113
情书的邮戳
情书的邮戳 2021-01-30 14:19

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         


        
5条回答
  •  温柔的废话
    2021-01-30 14:41

    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.

提交回复
热议问题