0
2

More than 3 years have passed since last update.

CarrierWave、MiniMagickでリサイズしたい【確認画面付】

Posted at

CarrierWave、MiniMagickを使用した画像投稿のリサイズ

uploaders/post_image_uploader.rb
class PostImageUploader < CarrierWave::Uploader::Base
  include CarrierWave::MiniMagick
  storage :file

  def store_dir
    "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
  end

  ## 追記
  process :resize_to_fit => [300, 300]
  version :thumb do
    process :resize_to_fit => [400, 400]
  end
  ## ここまで
end

確認画面がある場合【おまけ】

ルーティング

routes.rb
  resources :posts do
    collection do
      post :confirm
    end
  end

コントローラー

posts_controller.rb
  def confirm
    @post = Posg.new(post_params)
    render :new if @post.invalid?
  end

ビュー(new)

new.html
<%= form_with(model: post, local: true, url: confirm_posts_path) do |form| %>
  <% if post.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(post.errors.count, "error") %> 画像が保存できませんでした:</h2>

      <ul>
      <% post.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= form.label :画像の説明 %>
    <br>
    <%= form.text_field :title %>
    <br>
    <%= form.label :画像 %>
    <br>
    <%= image_tag(@post.image.url) if @post.image && @post.image.url %>
    <%= form.file_field :image %>
    <%= form.hidden_field :image_cache %>
  </div>

  <div class="actions">
    <%= form.submit %>
  </div>
<% end %>

ビュー(confirm)

confirm.html
<h1>確認画面</h1>

<%= form_with(model: @post, url: posts_path, local: true) do |form| %>
<p>コメント:<%= @post.title %></p>
<%= image_tag(@post.image.url) if @post.image && @post.image.url %>
<%= form.hidden_field :image_cache %>
<%=form.hidden_field :title %>
<br>
<button type="button" name="button">
  <%= form.submit "投稿する" %>
</button>
<button type="button" name="button">
  <%= form.submit "戻る", name: "back" %>
</button>
<% end %>

以上です!

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