LoginSignup
7
7

More than 5 years have passed since last update.

Paperclipで追加されるカラムの位置を指定する

Posted at

Railsで画像アップロードを行うためにPaperclipを使ったときに、カラムの位置が気に入らなかったので変更する方法をメモ。

:afterを追加してみる(失敗例)

rails g paperclip user photoで作成されたファイルに、:after引数を追加してみます。

add_attachment_photo_to_users.rb
class AddAttachmentPhotoToUsers < ActiveRecord::Migration
  def self.up
    change_table :users  do |t|
      t.attachment :photo, :after => :id
    end
  end

  def self.down
    drop_attached_file :users, :photo
  end
end

このままrake db:migrateを実行すると、
以下のカラムが既存のusersテーブルの末尾に追加されてしまいました。

  • photo_file_name
  • photo_content_type
  • photo_file_size
  • photo_updated_at
  • {:after=>:id}_file_name
  • {:after=>:id}_content_type
  • {:after=>:id}_file_size
  • {:after=>:id}_updated_at

paperclip-3.5.2/lib/paperclip/schema.rbを覗いてみると以下のようになっていました。

paperclip-3.5.2/lib/paperclip/schema.rb
module Schema
  COLUMNS = {:file_name    => :string,
             :content_type => :string,
             :file_size    => :integer,
             :updated_at   => :datetime}
(中略)
  module TableDefinition
    def attachment(*attachment_names)
      attachment_names.each do |attachment_name|
        COLUMNS.each_pair do |column_name, column_type|
          column("#{attachment_name}_#{column_name}", column_type)
        end
      end
    end

見ての通り、渡された引数は全てカラム名として使われてしまい、制約を加えることはできません。

ということで、t.attachmentを使った場合はカラムの位置は「指定できない」ようです。

全て書き直す(結論)

結局のところ全て手で書き直すことになります(最初のrails gも無駄になります)。

add_attachment_photo_to_users.rb
class AddAttachmentPhotoToUsers < ActiveRecord::Migration
  def self.up
    add_column :users, :photo_file_name,    :string,   :after => :id
    add_column :users, :photo_content_type, :string,   :after => :photo_file_name
    add_column :users, :photo_file_size,    :integer,  :after => :photo_content_type
    add_column :users, :photo_updated_at,   :datetime, :after => :photo_file_size
  end

  def self.down
    remove_column :users, :photo_file_name
    remove_column :users, :photo_content_type
    remove_column :users, :photo_file_size
    remove_column :users, :photo_updated_at
  end
end

残念。

7
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
7