ムカデノワラジ

ムカデノワラジ

ガジェット・Webサービス・プログラミング・エンタメについて書く雑記ブログ

MENU

Rails 画像アプロード

Gemfile

gem "carrierwave"

bundle install

 

$ rails g uploader img

$ rails g model Img image:string

$ rails db:migrate

 

app/uploaders/img_uploader.rb

class Image < ApplicationRecord
  mount_uploader :image, ImgUploader
end

 

app/controllers/imgs_controller.rb

class ImgsController < ApplicationController
  def show
     @imgs = Img.all
  end

def create
  @img = Img.new(permit_params)
  @img.save!
  redirect_to action: 'show'
end

 private
  def permit_params
    params.require(:img).permit(:image)
  end
end

views/imgs/show.html.haml

- @imgs.each do |img|
  %p
    = image_tag img.image.url
    = form_for :img, url: "imgs/" do |f|
    = f.file_field :image
    = f.submit

 

config/routes.rb

  get "/imgs", to: "imgs#show"
  post "/imgs", to: "imgs#create"