--Select an image. --Preview display before registering the image in the DB. ** If you want to see only the preview function, please read only the setting of JQuery below **
ruby 2.5.7 rails 5.2.4.3 It is possible to set jQuery.
This time, we will use "Refile". Refile is a file upload library for applications. ** Refile has the following features. ** **
-Images can be easily incorporated. -Thumbnails can be generated. -You can set the file upload destination.
In addition, this time, we have also added a gem (MiniMagick) that performs image processing such as size adjustment.
Gemfile
...
#Image posting gem
gem "refile", require: "refile/rails", github: 'manfe/refile'
#Image processing (size adjustment, etc.) gem
gem "refile-mini_magick"
When you add a gem, run the bundle install command.
Add a column to save the image. The column name is set with an id such as "image_id". (Data type is string) Let's reflect it in the database with the following command
python
$ rails db:migrate
To use Refile, you need to add an attachment method to your model. The attachment method is required for the refile to access the specified column. This makes it possible to acquire and upload images that exist in the DB. The column name is image_id, but I don't add _id here.
Let's write in the model
attachment :image
Please add an image. Under> private def arbitrary name params.require (: model name) .permit (: column name)
end This time, ** image ** will be entered in the column name.
ruby:new.html.rb
<%= form_for(model,url:Contains url or path) do |f| %>
<div class="item-image">
<%= attachment_image_tag from_Contains the model used in for, :image, class: "img-square", fallback: "no_image.jpg ", size:"300x300" %>
</div>
<%= f.attachment_field :image, placeholder: "image" %>
</div>
<%= f.submit "Registration"%>
・ This time, I would like to write
Recommended Posts