【问题标题】:How to check if attachment is new in Rails' ActiveStorage?如何检查 Rails 的 ActiveStorage 中的附件是否是新的?
【发布时间】:2019-10-14 09:25:14
【问题描述】:

在我的 Rails 5.2.2 应用程序中,我使用 Active Storage 将 logos 附加到 profiles

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

有没有办法在 model 中做同样的事情,即检查附件是否真的是新的,然后根据它设置 logo_active 属性?

我玩弄了 Rails 的 new_record? 方法,但无济于事。

【问题讨论】:

  • 您找到解决方法了吗?今天经历了这个。

标签: ruby-on-rails rails-activestorage


【解决方案1】:

我建议编写一个小型服务来为您更新个人资料并处理徽标更改。例如。像这样:

# 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

如果您更喜欢回调而不是服务,您可以按照this question 中所述为 ActiveStorage 模型创建回调

【讨论】:

    【解决方案2】:

    【讨论】:

      猜你喜欢
      • 2018-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多