A gem that allows you to easily add file uploads.
After adding the following to Gemfile
, execute the command to install the gem.
gem 'carrierwave'
$ bundle install
Running the rails g uploader uploader name
command creates the app/uploaders/image_uploader.rb
file.
This time, the uploader name is image
.
$ rails g uploader image
mount_uploader: Uploader name, class name
will be added to the associated model.
class Post < ApplicationRecord
mount_uploader :image, ImageUploader
end
Create a controller to upload the image. Create as usual without being aware of uploading images. Since there are text and image columns, the strong parameters are described as follows.
class PostsController < ApplicationController
private
def post_params
params.permit(:image, :content)
end
end
Create a form to upload the image. Create as usual without being aware of uploading images. For example, it looks like this.
<%= form_with url: "/posts/create" do |f| %>
<div class="form">
<%= f.label "Posting a photo" %><br>
<%= f.file_field :image %><br>
<%= f.text_area :content, value: @post.content %><br>
<%= f.submit "Post" %>
</div>
<% end %>
When you upload an image using this form, the image will be saved in the public/uploads
folder.
By adding <% if @ user.image?%>
, You can check whether the image has been set and conditionally branch depending on whether the image is set or not.
To display the saved image, call it with image_tag
.
<%= image_tag @post.image_url %>
Adding if @ post.image?
will prevent you from getting an error when there is no image.
<%= image_tag @post.image_url if @post.image? %>
Recommended Posts