こんにちは!kossyです!
本日気になったニュースはこちら
thebridge.jp
インターネットの登場で情報の非対称性はかなり緩和されたと思うのですが、
それでもなお一定数は存在していると思います。
この企業の事業は情報の非対称性の緩和にかなり貢献するのではないでしょうか。
さて、今回はRails5.2系から新しく導入されている、Active_Storageの開発環境での使い方について、
ブログに残してみたいと思います。
環境
Rails 5.2.1
Ruby 2.5.1
MacOS Mojave
尚、Active_Storageについて絞って記述するので、
routing、controllerの設定、細かなビューの記述については割愛しています。
Active_Storage利用準備
ターミナルで下記のコマンドを実行します。
$ rails active_storage:install => Copied migration 20181122043208_create_active_storage_tables.active_storage.rb from active_storage $ rails db:migrate
画像を添付できるようにモデルを編集
任意のモデルファイルにhas_one_attahedメソッドを用いて、
1つのコンテンツに1つの画像を紐づけることを、
その画像をコンテンツモデルからimageと呼ぶことをRailsに伝えています。
app/models/任意のモデルファイル(ここではContentとしておきます) Class Content < ApplicationRecord has_one_attached :image(任意) end
ビューファイル編集
任意のビューファイル(ここではapp/views/contents/new.html.slimとします) * bootstrapを使っています = form_with model: content, local: true do |f| - if task.errors.present? ul#error_explanation - task.errors.full_messages.each do |message| li= message .form-group = f.label :image = f.file_field :image, class: 'form-control' = f.submit '登録する', class: 'btn btn-primary'
show.html.slimにimage_tagを追加
動作確認のためにshow.html.slimを変更します。
任意の位置にimage_tagを追加します。
= Content.human_attribute_name(:image) = image_tag @content.image if @content.image.attached?
これでファイルの保存ができます。