Array Attribute for Ruby Model

前端 未结 5 2112
情书的邮戳
情书的邮戳 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:28

    Migration:

    t.text :thearray, :default => [].to_yaml
    

    In the model use serialize:

    class MyModel
      serialize :thearray, Array
      ...
    end
    

    As Marnen says in his answer, it would be good to know what kind of info you want to store in that array, a serialized attribute may not be the best option.

    [Marten Veldthuis' warning] Be careful about changing the serialized array. If you change it directly like this:

    my_model.thearray = [1,2,3]
    

    That works fine, but if you do this:

    my_model.thearray << 4
    

    Then ActiveRecord won't detect that the value of thearray has changed. To tell AR about that change, you need to do this:

    my_model.thearray_will_change!
    my_model.thearray << 4
    

提交回复
热议问题