コレグレーデギネード

WindowsとかUbuntuとかRubyとかRailsとか

Rails3.1以降で既存のテーブルにカラムを追加するマイグレーションファイルの書き方。CarrierWave編

やりたいこと。
 ・CarrierWaveで画像をアップロード。
 ・既にあるReportクラス(テーブル)に画像カラムを追加。

ReportクラスのマイグレーションファイルVer.3.0(Ver.3.1以降へアップデートする前)

class CreateReports < ActiveRecord::Migration
  def self.up
    create_table :reports do |t|
      t.string :title
      t.text :body
      t.timestamps
    end
  end

  def self.down
    drop_table :reports
  end
end

同じくReportクラスへカラムを追加した時のマイグレーションファイル。

class AddInactiveToReports < ActiveRecord::Migration
  def self.up
    add_column :reports, :inactive, :boolean
  end
  def self.down
    remove_column :reports, :inactive
  end
end

RailsVersion3.2.12で作業

画像アップロード用のクラスを作成。

$ rails g uploader image
   identical  app/uploaders/image_uploader.rb

Reportクラスに画像アップロード用のカラムを追加するためにマイグレーションファイルをコマンドで作成。

$ rails g migration AddImageToReports image:string
      invoke  active_record
      create    db/migrate/20130226034127_add_image_to_reports.rb

20130226034127_add_image_to_reports.rb

class AddImageToReports < ActiveRecord::Migration
  def change
    add_column :reports, :image, :string
  end
end

上記のようにchangeメソッドで記述される。Ver.3.0までのself.upやself.downという記述よりもドライ。

rakeタスクを実行して最新のバージョンに。

$ rake db:migrate
(in /RAILS_ROOT)
==  AddImageToSeminars: migrating =============================================
-- add_column(:reports, :image, :string)
   -> 0.0325s
==  AddImageToReports: migrated (0.0329s) ====================================

app/models/report.rbに追記。

  attr_accessible :image
  mount_uploader :image, ImageUploader

app/views/reports/_form.html.erbの編集。

#<%= form_for(@report) do |f| %>
#↓
<%= form_for @report, :html => {:multipart => true}  do |f| %>

app/views/reports/show.html.erbに追記。

<%= image_tag @report.image_url.to_s %>

アップロードしたファイルはpublic/uploads/report/[id]/[ファイル名]で保存される。