【问题标题】:undefined method `marked_for_destruction?' CarrierWave, RMagick未定义的方法“marked_for_destruction?” CarrierWave,RMagick
【发布时间】:2016-12-14 11:28:09
【问题描述】:

我正在通过 Carrierwave 上传的裁剪图像的功能。这是我关注的RailsCast video on Youtube

但在上传器中包含 RMagick 后,我收到:

undefined method `marked_for_destruction?' for #<ImageUploader:0x007fe86634fcf0>

我怎么想的。我没有在任何地方调用过这个方法。但是,如果它没有定义,让我们定义它!它奏效了!但后来我查看了更多关于这个方法的信息,发现它是内置在 Active Record Autosave Association 模块中的。从文档中,关于这种方法:

返回此记录是否将作为 父母保存交易。

仅当为此启用父级上的 :autosave 选项时才有用 关联模型。

但我没有将autosave: true 传递给任何对象!

那么,我的第一个问题 - 它是默认以某种方式完成的吗?

2 - 在 RailsCast 教程中他没有定义这个方法。为什么我必须这样做?

3 - 我通过下面的代码。有什么错误吗?

4 - 如果可能的话,谁能解释一下这个过程是如何运作的?

非常感谢!

product.rb:

  has_one :image
  validates :image, presence: true
  mount_uploader :image, ImageUploader

products_controller.rb:

  def create
    @product = Product.new(product_params)
    @product.category_id = params[:category_id]
    @product.user_id = current_user.id

    respond_to do |format|
      if @product.save
        if params[:product][:image].present?
          format.html { render :crop }
        else
          format.html { redirect_to @product, notice: 'Product was successfully created.' }
          format.json { render :show, status: :created, location: @product }
        end
      else
        format.html { render :new }
        format.json { render json: @product.errors, status: :unprocessable_entity }
      end
    end
  end

image_uploader.rb:

class ImageUploader < CarrierWave::Uploader::Base

  include CarrierWave::RMagick

  def marked_for_destruction?
    @marked_for_destruction
  end

  def mark_for_destruction
    @marked_for_destruction = true
  end

  storage :file

  def store_dir
    "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
  end

  version :large do
    resize_to_limit(600,600)
  end
end

【问题讨论】:

    标签: carrierwave ruby-on-rails-5 rmagick


    【解决方案1】:

    如果您使用的是 Rails 5:

    打开new_framework_defaults.rb并更改:

    Rails.application.config.active_record.belongs_to_required_by_default = true
    

    Rails.application.config.active_record.belongs_to_required_by_default = false
    

    config.active_record.belongs_to_required_by_default 是一个布尔值 如果belongs_to,值并控制记录是否验证失败 关联不存在。

    【讨论】:

    • 谢谢,您能否通过写下这是因为 Rails5 belongs_to 所需的标志默认设置为 true 以及它与我的问题有什么关系来改进您的答案。我敢打赌,人们会对此表示感谢。我不再从事那个项目了,所以不能轻易测试这个
    • 作为一个爱好者,我同意popStar。您建议我在没有真正解释我在做什么或这种方法在做什么的情况下对 Rails 进行更改。感觉真的很危险。
    • 你可以把它放在 config/application.rb 里面的类 Apllication
    【解决方案2】:

    在你的 *_uploader.rb 文件中只写函数:

      def marked_for_destruction?
    
      end
    

    【讨论】:

      猜你喜欢
      • 2013-05-01
      • 2016-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-26
      • 1970-01-01
      • 1970-01-01
      • 2011-09-21
      相关资源
      最近更新 更多