3

我有一些模型在其他路径上共享相同的功能。所以我决定将这些方法放在一个模块中,并在模型中设置路径。我的问题是我无法访问模块中的属性。

模型:

class Job < ActiveRecord::Base
  include ImageModel

  image_dir = "jobs"
end

模块:

module ImageModel
  extend ActiveSupport::Concern

  def delete_image
      unless pic_link == "" || pic_link == nil
        begin
          if File.delete(Rails.root.join("public", "images", image_dir, pic_link))
            return true
          else
            return false
          end
        rescue
          return true #an error occured but when the image does not exist we still return true
        end
      end

      return true
    end

    def replace_image(new_image)
      File.open(Rails.root.join("public", "images", image_dir, new_image.original_filename), "wb") do |f|
        if f.write new_image.read
          delete_image
          pic_link = new_image.original_filename
          return true #everything went fine
        else
          return false #return false if new image could not be written
        end
      end
    end
end

我得到的错误:

undefined local variable or method `image_dir' for #<Job:0x007f8a93b9e8d8>

在这条线上:

File.open(Rails.root.join("public", "images", image_dir, new_image.original_filename), "wb") do |f|

我错过了什么还是我监督了一些重要的事情?

菲利克斯

4

2 回答 2

1

我认为模块的设计还有改进的空间。但是对于这个特定的问题,这里是快速修复。

class Job < ActiveRecord::Base
  include ImageModel

  def image_dir
    "jobs"
  end
end
于 2013-09-18T18:27:22.330 回答
0

您应该image_dir = "jobs"在模块本身中定义您的。因为您将模块包含在模型中,并且您的模块无法获得声明,所以您已经在模型中完成了。

或者您可以更改delete_image方法以获取参数:

def delete_image(image_dir)
      unless pic_link == "" || pic_link == nil
        begin
          if File.delete(Rails.root.join("public", "images", image_dir, pic_link))
            return true
          else
            return false
          end
        rescue
          return true #an error occured but when the image does not exist we still return true
        end
      end

      return true
    end

在你调用那个方法的地方,传递一个像这样的参数:

 delete_image("jobs")

在方法的情况下相同replace_image

 def replace_image(new_image, image_dir)
      File.open(Rails.root.join("public", "images", image_dir, new_image.original_filename), "wb") do |f|
        if f.write new_image.read
          delete_image
          pic_link = new_image.original_filename
          return true #everything went fine
        else
          return false #return false if new image could not be written
        end
      end
    end

希望它会有所帮助。谢谢

于 2013-09-18T10:20:18.757 回答