簡體   English   中英

Rails活動存儲,在has-many_attached時更新映像

[英]Rails active storage, update the image when has-many_attached

我將rais api用於后端,並對前端進行響應。

我正在使用Rails主動存儲來處理圖像。

在我的rails應用程序中,我有模式名稱Post

class Post < ApplicationRecord
  has_many_attached :pictures

  def picture_url
    if self.pictures.attached?
      self.pictures.map do |picture|
        Rails.application.routes.url_helpers.rails_blob_path(picture, 
        only_path: true)
      end
    else
      nil
    end
  end
end

所以根據上面的一篇post可以有很多圖片。

現在,我在更新帖子的圖片時遇到問題。

情況1:假設我有一個帖子,說“ p1”,p1現在有3張圖片。 現在,如果我想從p1中刪除一張圖片,並添加一個新圖片代替刪除的圖片。 我將如何在控制器中處理它。

情況2:我只想保留3張圖片中的一張。 這意味着我要刪除特定的2張圖像。

我對posts_controller.rb update操作如下:

  def update
    post = Post.find(params[:id])
    if post.update_attributes(message: params[:message], picture: 
       params[:picture])
      render_success(:ok, post, meta: { message: 'Post updated' })
    else
      render_error(422, post.errors, message: 'Failed to update post')
    end
  end

https://matias.svbtle.com/rails-droplets-2-using-activestorage-for-has-many-attached-images-with-nested-forms-and-deletion-part-1

這應該為您提供一個良好的起點。 非常感謝我應該從那里復制並粘貼代碼,但是您實際上需要從頭開始執行。

這意味着如果更新中有任何附件詳細信息,則首先刪除所有當前附件,然后關聯新附件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM