Rails: Adding migration to add an array (default empty)

后端 未结 3 948
小蘑菇
小蘑菇 2020-12-24 12:14

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 contai

3条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-24 12:48

    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
    

提交回复
热议问题