Array Attribute for Ruby Model

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

    Create a model with a text field

    > rails g model Arches thearray:text
      invoke  active_record
      create    db/migrate/20111111174052_create_arches.rb
      create    app/models/arches.rb
      invoke    test_unit
      create      test/unit/arches_test.rb
      create      test/fixtures/arches.yml
    > rake db:migrate
    ==  CreateArches: migrating ===================================================
    -- create_table(:arches)
       -> 0.0012s
    ==  CreateArches: migrated (0.0013s) ==========================================
    

    edit your model to make the field serialized to an array

    class Arches < ActiveRecord::Base
      serialize :thearray,Array
    end
    

    test it out

    ruby-1.8.7-p299 :001 > a = Arches.new
     => # 
    ruby-1.8.7-p299 :002 > a.thearray
     => [] 
    ruby-1.8.7-p299 :003 > a.thearray << "test"
     => ["test"] 
    

提交回复
热议问题