Explanation from image saving to display using Active Storage. In my last post, I explained how to install Active Storage.
Link ↓ Flow to implement image posting function using ActiveStorage
has_one_attached method to associate each record with the image file in a one-to-one relationship.
Describe in the model file you want to link
class model< ApplicationRecord has_one_attached :file name end
For the file name, set the name when calling. It also becomes a parameter key.
ex):image, :file etc
As an image, it feels like there is a file name column with attachments in it.
By making this association,
You can access the attached file with
model name.file name.
As mentioned when defining the association, use the file name as the parameter key. Even at this time, the image that the column is formed will be applicable.
The above is the flow until storage.
The following is the flow until it is displayed.
Generate an img tag in HTML using a helper method called ʻimage_tag method`.
<%= image_tag model name.file name%> <%= image_tag message.image %> #Example
Since it is associated, the image can be displayed by describing only
model name.file name.
Basically, the image can be displayed up to this point. However, if there is no image at this rate, an error will occur.
Conditionally branch to the previous ʻimage_tag method` with an if statement.
<%= image_tag message.image, if message.image.attached? %>
If an image is attached with the ʻattached? method`, it returns true and is read. If no image is attached, it returns false, is not loaded and no error occurs.
variant method, which is a method that can be used when ActiveStorage is installed.
If you add it to the above code,
<%= image_tag message.image.variant(resize: '500×500'), if message.image.attached? %>
If you specify the display size of the image, it will not be larger than that.
In the current situation, if you imagine LINE, you will get an error if you do not have both text and image. Since it is not easy to use, the specification is that either text or image should exist.
validates :message, presence: true, unless: :was_attacher? def was_attached? self.image.attached? end
If the return value of the method is false, validation is verified. (If message does not exist)
It's too convenient to be able to easily access images just by associating! !!