LoginSignup
58
72

More than 5 years have passed since last update.

画像投稿機能

Posted at

画像投稿機能

多くの人が画像投稿機能に関する記事を書いているが自分もアウトプットがてら記事書いていこうと思う。

1.DBのカラムを調べる。

初めに画像を投稿してDBに保存するには保存できるカラムが必要。
なのでそのカラムの有無を調べよう。
db/schema.rbを開く。

db/schema.rb
create_table "posts", force: :cascade do |t|
    t.string "title"
    t.text "text"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.string "img"
    t.integer "user_id"
  end

私の場合はimgカラムがあるので大丈夫。カラムがない人はimgカラムあるいはimageカラムを追加しよう。

2.カラムの追加

画像を保存するためのimgカラムを追加。

ターミナル
$ rails g migration AddImgToPosts img:string

するとPostsテーブルにimgというカラムが追加される。続けて、

ターミナル
$ rails db:migrate

をして保存する。

3.Carrierwaveのインストール

Gemfileを開きcarrierwaveをインストール

Gemfile
gem 'carrierwave', '~> 1.3', '>= 1.3.1'
$ bundle 

を実行して完了。

4.mount_uploaderを準備する

ターミナル
$ rails g uploader img

ターミナルでこれを実行するとuploadersディレクトリとimg_uploader.rbファイルが生成される。
※imgと書いているところは追加したカラムと合わせてください。

例えばimageカラムを追加したのであれば

$ rails g uploader image

です。

app/models/post.rbに移動。

app/models/post.rb
class Post < ApplicationRecord
 mount_uploader :img, ImgUploader
end

と記述する。

5.コントローラを変更する

app/controllers/posts_controller.rb
class PostsController < ApplicationController
: 
private
 def post_params
  params.require(:post).permit(:title, :text, :img)
 end
end

6.ビューを変更

フォームのパーシャルファイルを変更し、imgの欄を追加する。
画像をアップロードするにはfile_fieldというものを使う。

app/views/posts/_form.html.erb
<%= form_for (@post) do |f| %>
 :
 :
 <%= f.label :画像 %><br />
 <%= f.file_field :img, class: "image" %>
 :
 <%= f.submit %>

<% end %>
app/views/posts/show.html.erb
<p>
  <strong>Text:</strong>
  <%= @post.text %>
</p>
<p>
  <strong>Image:</strong>
  <%= image_tag @post.img.url%>
</p>

※インスタのように絶対に画像をアップロードするアプリだと上の<%= image_tag %>でいいが画像をアップしたりしなかったりだとこのままではエラーになるので以下のように
if @post.img?
を付け加えよう。

app/views/posts/show.html.erb
<p>
  <strong>Text:</strong>
  <%= @post.text %>
</p>
<p>
  <strong>Image:</strong>
  <%= image_tag @post.img.url if @post.img? %>
</p>

7.画像の削除

app/views/posts/_form.html.erb
 <%= f.label :画像 %><br />
 <%= f.file_field :img, class: "image" %>
に続いて、
 <p><%= f.check_box :remove_img %>画像を削除する</p>

を加える。

最後にremove_imgを追加。

app/controllers/posts_controller.rb
class PostsController < ApplicationController
: 
private
 def post_params
  params.require(:post).permit(:title, :text, :img, :remove_img)
 end
end
58
72
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
58
72