0

Following some other StackOverflow questions and other articles on the web, I was trying to add an array attribute to one of my models.

rails g migration add_new_attribute_to_my_model new_attribute:text

Then in the migration file

def change
  add_column :my_model, :new_attribute, :text, default: [].to_yaml
end

(because if I do

def change
  add_column :my_model, :new_attribute, :text, default: [], array:true
end

I get TypeError: can't quote Arrayin the migration).

rake db:migrate

In my_model_controller.rb

class MyModelController < ApplicationController

  class MyModel < ActiveRecord::Base
    serialize :new_attribute,Array
  end

  ...

end

But like this I get

a = MyModel.new
=>MyModel ... new_attribute: "--- []\n">
a.new_attribute << "asd"
=>MyModel ... new_attribute: "--- []\nasd">

Where should I fix the process?

strivedi183
  • 4,749
  • 2
  • 31
  • 38
fabdurso
  • 2,366
  • 5
  • 29
  • 55
  • Have you see this post? https://stackoverflow.com/questions/21312278/storing-arrays-in-database-json-vs-serialized-array – gwalshington Aug 29 '18 at 20:38
  • 1
    If you're defining MyModel with the serializer inside of MyModelController, then the way you'd refer to it in Rails console is MyModelController::MyModel.New. Do you have a second copy of MyModel some place (such as app/models) that does not include your serializer code? – Billy Kimble Aug 29 '18 at 20:39
  • Which database are you using? Some support array columns, some require `serialize` and YAML hackery to emulate arrays. – mu is too short Aug 29 '18 at 20:56
  • @gwalshington yes but It didn't help. @bkimble when doing `MyModelController::MyModel.New` it's working fine! What would be the best way to achieve that by just doing `MyModel.new`? – fabdurso Aug 29 '18 at 21:01
  • @bkimble achieved by placing the `serialize` in app/models/my_model`. Thanks! – fabdurso Aug 29 '18 at 21:06
  • 1
    No problem. You shouldn't ever be storing ActiveRecord model code inside your Controllers ;) (almost) Everything has its place in Rails. – Billy Kimble Aug 29 '18 at 21:09

0 Answers0