0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Railsでファイル(画像)をレコードに保存する方法

Posted at

最近、railsの勉強を始めました。
基本的なCRUD処理を公式のドキュメントで学び終えたあと、
レコードに写真を追加したいと思い、調べながらなんとかできたので備忘録を残します。

概要

写真付きのブログを作ります。
画像の扱いは、下記を参考にしました。Active Strageを使用します。

準備

新しいrailsアプリを作成します

rails new blog

モデル設計

タイトル、本文、写真のフィールドをもつモデルを作成します
今回、画像のフィールドを"image"としました。型はstringにします。

bin/rails generate model Blog title:string body:string image:string

Active Strageの設定

Gemfileに下記を追記してください

gem "image_processing", ">= 1.2"

追加したら、下記を実行してimage_processingをインストールします。

bundle install

モデルの編集

下記のように編集します。
has_one_attachedにimageを指定します
これでimageフィールドに写真が割り当てられるようなイメージです

blog.rb
class Blog < ApplicationRecord
    has_one_attached :image do |attachable|
        attachable.variant :thumb, resize_to_limit: [100, 100]
    end
end

コントローラ

最低限のみ実装しています

blogs_controller.rb
class BlogsController < ApplicationController
   #一覧画面
  def index
    @blogs = Blog.all
  end

  #新規作成
  def new
    @blog = Blog.new
  end

   #新規作成処理
  def create
    @blog = Blog.new(blog_params)
    if @blog.save
      redirect_to @blog
    else
      render :new, status: :unprocessable_entity
    end
  end

  private
  def blog_params
    params.expect(blog: [ :title, :body, :image ])
  end

end

ルート

routes.rb
  get "/blogs", to: "blogs#index" #一覧
  get "/blogs/new", to: "blogs#new"#新規作成画面
  post "/blogs", to: "blogs#create"#新規作成処理

ビュー

views>blogsにindex.html.erbとnew.html.erbを作成して
以下のように編集します

index.html.erb
<h1>写真付きブログ一覧</h1>


<div id="blogs">
  <% @blogs.each do |blog| %>
    <div>
        <%= blog.title %>
        <%= image_tag blog.image %>
    </div>
  <% end %>
</div>

ファイルアップロードの部分は、"form.file_field"を使ういます

new.html.erb
<h1>ブログ作成</h1>


<%= form_with model: @blog do |form| %>
  <div>
    <%# タイトル %>
    <%= form.label :title %>
    <%= form.text_field :title %>

    <%# 本文 %>
    <%= form.label :body %>
    <%= form.text_field :body %>

    <%# 写真 %>
    <%= form.file_field :image %>
  </div>

  <div>
    <%= form.submit %>
  </div>
<% end %>

これで、bin/rails serverでローカルサーバーを立ち上げ、
"127.0.0.1:3000/blogs/new"にアクセスして投稿します。
"127.0.0.1:3000/blogs"にアクセスすると、画像が表示されることが確認できると思います。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?