Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I create an array as a column in a table in Rails?

Why can't I do something like this:

class CreateModels < ActiveRecord::Migration
  def self.up
    create_table :fruit do |t|
      t.array :apples
    end
  end
end

Is there some other way to make an array ("apples) be an attribute of an instance of the Fruit class?

like image 824
steven_noble Avatar asked Jul 06 '11 22:07

steven_noble


People also ask

Can you add arrays in Ruby?

This can be done in a few ways in Ruby. The first is the plus operator. This will append one array to the end of another, creating a third array with the elements of both. Alternatively, use the concat method (the + operator and concat method are functionally equivalent).

Can arrays contain arrays Ruby?

Arrays can contain any combination of Ruby data types -- booleans, integers, strings, or even other collections in the form of nested arrays and hashes. A nested, or multidimensional array, is an array whose individual elements are also arrays.

How do you add a value to an array in Ruby on Rails?

Ruby | Array append() function Array#append() is an Array class method which add elements at the end of the array. Parameter: – Arrays for adding elements. Return: Array after adding the elements at the end.


3 Answers

In Rails 4 and using PostgreSQL you can actually use an array type in the DB:

Migration:

class CreateSomething < ActiveRecord::Migration
  def change
    create_table :something do |t|
      t.string :some_array, array: true, default: []
      t.timestamps
    end
  end
end
like image 193
Adam Waite Avatar answered Oct 11 '22 21:10

Adam Waite


Check out the Rails guide on associations (pay particular attention to has_many).

You can use any column type supported by your database (use t.column instead of t.type), although if portability across DBs is a concern, I believe it's recommended to stick to the types explicitly supported by activerecord.

It seems kind of funny for fruit to have_many apples, but maybe that is just an example? (I would expect apples to be a subclass of fruit).

like image 39
cam Avatar answered Oct 11 '22 20:10

cam


You may use serialize. But if an Apple is going to be an AR object, use associations.

like image 2
Pablo Castellazzi Avatar answered Oct 11 '22 19:10

Pablo Castellazzi