Rails: Adding migration to add an array (default e

2019-03-11 00:36发布

问题:

I'm trying to add a column called share to one of my resources. The idea is that users can upload documents and share them with other (specific) users, and the array contains the emails of those that the user wants to share with.

I tried adding a migration with the code

class AddShareToDocuments < ActiveRecord::Migration
  def change
    add_column :documents, :share, :array, :default => []
  end
end

But when I open up rails console in the command prompt, it says that share:nil and user.document.share.class is NilClass.

Creating a new array in the rails console sandbox by typing

newarray = []

says that newarray.class is Array.

Can anyone spot what I'm doing wrong?

回答1:

Rails 4 the PostgreSQL Array data type

In terminal

rails generate migration AddTagsToProduct tags:string

class AddTagsToProduct < ActiveRecord::Migration
  def change
    add_column :products, :tags, :string, array: true, default: []
  end
end

https://coderwall.com/p/sud9ja/rails-4-the-postgresql-array-data-type



回答2:

if you want support all databases you must serialize the array in a String

class Documents < ActiveRecord::Base
 serialize :share
end

class AddShareToDocuments < ActiveRecord::Migration
 def change
   add_column :documents, :share, :string, :default => []
 end 
end

In case of Postgresql and array datatype I found https://coderwall.com/p/sud9ja



回答3:

Arrays are not normally a type to be stored in a database. As michelemina points out, you can serialize them into a string and store them, if the type of the data in the array is simple (strings, int, etc). For your case of emails, you could do this.

If, on the other hand, you want to be able to find all of the User objects that a document was shared with, there are better ways of doing this. You will want a "join table". In your case, the join-table object may be called a Share, and have the following attributes:

class Share
  belongs_to :user
  belongs_to :document
end

Then, in your Document class,

has_many :shares
has_many :users, :through => :shares

As far as generating the migration, this may be hacky, but you could create a new migration that changes the type to "string" (Edit: correct code):

class AddShareToDocuments < ActiveRecord::Migration
  def up
    change_column :documents, :share, :string
  end
  def down
    change_column :documents, :share, :array, :default => []
  end
end