如何在Rails的ActiveStorage中检查附件是否为新文件?

5
在我的Rails 5.2.2应用程序中,我正在使用Active Storage来将“标志”附加到“个人资料”中:
class Profile < ApplicationRecord

  has_many_attached :logos

end

我该如何测试是否在更新时已附加了新的标志?
目前,我正在我的控制器中检查logos参数,这个方法运行良好:
class ProfileController < ApplicationController

  def update
    if params[:profile][:logos].present?
      @profile.logo_active = true # This is the important attribute I need to set
    end
    if @profile.update(profile_params)
      flash[:success] = "Profile updated."
      redirect_to profile_path
    end
  end

end

有没有一种方法可以在模型中做同样的事情,即检查附件是否实际上是新的,并根据此设置logo_active属性?
我尝试使用Rails的new_record?方法,但无法成功。

你找到解决这个问题的方法了吗?今天我也遇到了这个问题。 - Ricardo Green
2个回答

5

0
我建议编写一个小型服务,可以为您更新个人资料并处理标志更改。例如,像这样的东西:
# app/services/profile_updater.rb

class ProfileUpdater
  def self.call(params)
    profile = Profile.find(params.delete(:id))
    logos_was = profile.logos
    profile.assign_attributes(params)
    profile.logo_active = profile.logos != logos_was
    profile.save
  end
end

如果您更喜欢回调而不是服务,您可以尝试创建ActiveStorage模型的回调,如this question中所述。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接