【Rails】ActiveStorage 使用時に、フォームでバリデーションエラーが起こっても画像の指定を維持したい
ActiveStorageの話題
https://ryoito.jp/articles/957d6e99
code:ruby
結論から言うと、このように変更してあげれば画像の指定が保持されるようになります。
# app/models/book.rb
class Book < ApplicationRecord
has_one_attached :cover_image
+ attribute :cover_cache, :string
validates :title, presence: true
+ before_validation :set_cover_cache
+ private
+
+ def set_cover_cache
+ if cover_cache.present? && cover_image.blank?
+ self.cover_image = cover_cache
+ end
+ end
end
# app/controllers/books_controller.rb
class BooksController < ApplicationController
# new アクションや edit アクションなどは省略
private
def book_params
- params.require(:book).permit(:title, :cover_image)
+ params.require(:book).permit(:title, :cover_image, :cover_cache)
end
end
# app/views/books/_form.html.haml
= simple_form_for book do |f|
= f.input :title, autofocus: true
= f.input :cover_image, as: :file, input_html: { data: { direct_upload_url: rails_direct_uploads_path } }
+ = f.hidden_field :cover_cache, value: book.cover_image.signed_id if book.cover_image.attached?
= f.button :submit, class: 'btn-primary'