% rails active_storage:install
Install Active_storage and generate related files (migration, etc.)
%rails db:migrate
If you check Seaquel Pro and the following table is generated, it is successful so far. This completes the "container" for storing images.
class Message < ApplicationRecord
~Descriptions such as other associations are omitted~
has_one_attached :image
end
It may be easier to imagine saying "I made a pseudo image column" rather than an association.
Looking at the message table of seaquel_pro, the image column does not exist
However, due to has_one_attached described in the model, there is a "pseudo image column" in the messages table.
From this, the image information can be skipped in params in messages_controller.rb.
controllers/messages_controller.rb
class MessagesController < ApplicationController
def new
@message = Message.new
end
def create
@mesage = Message.create(message_params)
end
private
def message_params
params.require(:message).permit(:content, :image).merge(user_id: current_user.id)
end
end
<%= form_with model: @message, local: true do |form| %>
<%= form.text_area :content %><br>
<%= form.file_field :image %><br>
<%= form.submit %>
<% end %>
<% if @message.image.attached? %>
<%= image_tag @message.image %>
<% end %>
that's all! !!