Nội dung chính
Cài đặt ActiveStorage
rails active_storage:install
rake db:migrate
Gemfile
gem "image_processing"
app/models/article.rb
has_one_attached :image
app/controllers/articles_controller.rb
def article_params params.require(:article).permit(:image) end
app/views/articles/_form.html.slim
= f.label :image = f.file_field :image, accept: "image/png, image/jpg, image/jpeg, image/gif"
app/views/articles/show.html.slim
- if @article.image.attached? = image_tag @article.image.variant(resize: "640x480^", crop:"640x480+0+0", gravity: :center).processed
Một vài method cơ bản
Kiểm tra tồn tại
article.image.attached?
Download link
rails_blob_path(article.image, disposition: "attachment")
Delete
article.image.purge
Thiết lập để dùng trên Production
Gemfile
gem "aws-sdk-s3", require: false
config/storage.yml
amazon: service: S3 access_key_id: <%= ENV["AWS_ACCESS_KEY_ID"] %> secret_access_key: <%= ENV["AWS_SECRET_ACCESS_KEY"] %> region: ap-northeast-1 bucket: <%= ENV["AWS_BUCKET"] %>
config/environments/production.rb
config.active_storage.service = :amazon
Updated at 2023-05-09
Nếu bài viết có ích thì các bạn hãy chia sẻ nhé