Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 如何在ruby中将类方法更改为实例方法?_Ruby On Rails_Ruby - Fatal编程技术网

Ruby on rails 如何在ruby中将类方法更改为实例方法?

Ruby on rails 如何在ruby中将类方法更改为实例方法?,ruby-on-rails,ruby,Ruby On Rails,Ruby,现在,我面临创建实例方法的问题。 项在活动存储器中有多个映像 我创建了一个类方法,如下所示 def self.get_url(item) item.images.map do |image| Rails.application.routes.url_helpers.url_for(image) end end 这种课堂教学法效果非常好。 但是我想把这个方法改为实例方法,这样我就可以在没有参数项的情况下使用另一个地方 所以我希望它是这样的 de

现在,我面临创建实例方法的问题。 项在活动存储器中有多个映像

我创建了一个类方法,如下所示

  def self.get_url(item)
      item.images.map do |image|
        Rails.application.routes.url_helpers.url_for(image)
      end
  end
这种课堂教学法效果非常好。 但是我想把这个方法改为实例方法,这样我就可以在没有参数项的情况下使用另一个地方

所以我希望它是这样的

  def get_url
      item.images.map do |image|
        Rails.application.routes.url_helpers.url_for(image)
      end
  end
item.get_url
但我不能这样做,因为没有定义类似项的内容

我想这样使用它

  def get_url
      item.images.map do |image|
        Rails.application.routes.url_helpers.url_for(image)
      end
  end
item.get_url
如果你能帮助我,我将非常感激。 谢谢。

def self.get_url(item)
中,我假设
item
是类的一个实例,因此如果要创建实例方法,只需从
item.images
中删除
item
部分即可:

def get_url
  images.map do |image|
    Rails.application.routes.url_helpers.url_for(image)
  end
end

谢谢你的评论!我认为这将工作,但图像是附加到项目,所以我认为我需要它写。有很多附件:图片我刚刚试过,效果不错!非常感谢。