【问题标题】:Do Not purge image when updating record in Rails 6 Active Storage在 Rails 6 Active Storage 中更新记录时不要清除图像
【发布时间】:2021-06-02 19:29:12
【问题描述】:

我已经研究这个问题几天了,似乎找不到解决方案。

我在 Rails 6 中有一个模型,用于has_one_attached :image

用户可以创建新栏并附加图像。这很好用。

当用户编辑酒吧名称等酒吧信息并提交该信息时,Active Storage 默认会清除最初上传的图片,即使没有提交新图片。

在编辑过程中,如果用户没有提交新图像,并且只更改了记录,例如酒吧名称,我如何防止 Active Storage 自动清除图像?我想保留与 Bar 记录相关联的图像。

我在我的模型中尝试了dependent: :purge_later,但没有成功。我也尝试过在没有图像参数if bar_info.image.attached?

的情况下提交参数

我的模型 bar_info.rb

class BarInfo < ApplicationRecord
    belongs_to :user
    has_many :bar_specials, dependent: :destroy
    has_one_attached :image
    validates :user_id, presence: true
    validates :barname, presence: true, length: { maximum: 100 }
    validates :city, presence: true, length: { maximum: 50 }
    validates :state, presence: true, length: { maximum: 50 }
    validates :image, content_type: { in: %w[image/jpeg image/gif image/png],
                                            message: "must be a valid image format" },
                          size:         { less_than: 5.megabytes,
                                          message: "should be less than 5MB" }
end

我的控制器 bar_infos_controller.rb

class BarInfosController < ApplicationController
def update
        @bar_info = BarInfo.find(params[:id])
        @bar_info.user_id = current_user.id
        @bar_info.image.attach(params[:bar_info][:image])
        if @bar_info.update(bar_info_params)
            flash[:notice] = "Bar Info Updated!"
            redirect_to bar_info_path(@bar_info)
        else
            render "edit"
        end
end

private

        def bar_info_params
            attributes = [ :barname, :city, :state, :image ]
            params.require(:bar_info).permit(attributes)
        end
end

我的编辑视图_form.html.erb

<div class="row">
    <div class="col-md 6">
        <%= form_with(model: @bar_info, local: true) do |f| %>
        <%= render 'shared/error_messages', object: f.object %>

        <%= f.label "Bar Name (required)" %>
        <%= f.text_area :barname, placeholder: "Bar name here", class: "form-control", size: "70x1" %>

        <%= f.label "City (required)" %>
        <%= f.text_area :city, placeholder: "San Diego", class: "form-control", size: "70x1" %>

        <%= f.label "State (required)" %>
        <%= f.select :state, CS.states(:us), class: "form-control" %>

        <span class="image">
            <p>Upload an image of Bar here!</p>
            <%= f.file_field :image, accept: "image/jpeg,image/gif,image/png" %>
        </span>

        <%= f.submit "Submit", class: "btn btn-primary" %>
        <% end %>

        <script type="text/javascript">
            $("#bar_info_image").bind("change", function() {
                const size_in_megabytes = this.files[0].size/1024/1024;
                if (size_in_megabytes > 5) {
                    alert("Maximum file size is 5MB. Please choose a smaller file.");
                    $("$bar_info_image").val("");
                }
            });
        </script>
    </div>
</div>

bar_infos 路线:

bar_infos     GET    /bar_infos(.:format)          bar_infos#index
              POST   /bar_infos(.:format)          bar_infos#create
new_bar_info  GET    /bar_infos/new(.:format)      bar_infos#new
edit_bar_info GET    /bar_infos/:id/edit(.:format) bar_infos#edit
bar_info      GET    /bar_infos/:id(.:format)      bar_infos#show
              PATCH  /bar_infos/:id(.:format)      bar_infos#update
              PUT    /bar_infos/:id(.:format)      bar_infos#update
              DELETE /bar_infos/:id(.:format)      bar_infos#destroy

TL;DR 我想编辑一个酒吧的名称,但仍保留与它一起上传的原始图像。 Active Storage 当前会在更新时清除该映像。

谢谢。

【问题讨论】:

  • 如果您尝试在控制台更新Bar.find(1).update(name: 'something'),会发生什么?

标签: ruby-on-rails ruby-on-rails-6 rails-activestorage


【解决方案1】:

这是因为您的 update 控制器操作中的这一行:

      def update 
        ...
        @bar_info.image.attach(params[:bar_info][:image])
        ...
      end

如果用户没有在编辑操作中填写图像,您会将图像设置为nil,这会从 activestorage 中删除文件。您应该将此更新完全保留在 ActiveRecords update 操作上。您在允许的参数中有图像,因此它应该可以正常工作:

      def update
        @bar_info = BarInfo.find(params[:id])
        @bar_info.user_id = current_user.id

        if @bar_info.update(bar_info_params)
          flash[:notice] = "Bar Info Updated!"
          redirect_to bar_info_path(@bar_info)
        else
          render "edit"
        end
      end

private

      def bar_info_params
        attributes = [ :barname, :city, :state, :image ]
        params.require(:bar_info).permit(*attributes)
      end

(我也认为permit调用params.require(:bar_info).permit(*attributes)中应该有*)

【讨论】:

  • 谢谢你,我用你的解决方案更新了它,它工作正常。原始代码来自 Michael Hartl Ruby on Rails 第 6 版,供任何可能具有该背景的人使用。
猜你喜欢
  • 2018-10-24
  • 2019-11-01
  • 2020-11-04
  • 1970-01-01
  • 2019-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-13
相关资源
最近更新 更多