1

I am getting a:

NoMethodError in UsersController#show
undefined method `recreate_versions!' for "img1.jpg":String

when I call:

User.all.each do |user|
  user.photo.recreate_versions!
end

in my mounted uploader. My table column is called photo with a data type of String and is called by attr_accessible in my User model. Any ideas how to resolve this?

Here is my full code:

class PhotoUploader < CarrierWave::Uploader::Base
  include CarrierWave::RMagick
  include Sprockets::Rails::Helper

  storage :file

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

  def default_url

    "fallback/" + [version_name, "img1.jpg"].compact.join('_')
  end

  version :mini_thumb do 
    process :resize_to_limit => [50, 40]
  end

  version :thumb do
    process :resize_to_limit => [100, 100]
  end

  version :default do 
    process :resize_to_limit => [250, 250]
  end

  User.all.each do |user|
     user.photo.recreate_versions!
   end
end

Maybe I am not supposed to call recreate_versions from the mounted uploader?

EDIT:

Running

User.first.photo.class

in the console outputs:

  User Load (10.5ms)  SELECT "users".* FROM "users" ORDER BY "users"."id" ASC LIMIT 1
  User Load (10.5ms)  SELECT "users".* FROM "users" ORDER BY "users"."id" ASC LIMIT 1
 => PhotoUploader 

Then iterating through each user and calling recreate_versions!:

2.0.0p0 :003 > User.all.each do |user|
2.0.0p0 :004 >       user.photo.recreate_versions!
2.0.0p0 :005?>   end
User Load (1.1ms)  SELECT "users".* FROM "users"
User Load (1.1ms)  SELECT "users".* FROM "users"
NoMethodError: undefined method `read' for nil:NilClass

After checking for nil in the rails console this worked (still not sure where to put it though):

User.all.each do |user|
  user.photo.recreate_versions! if user.photo.present?
end 
4

3 回答 3

3

我在您的代码中注意到的一件事是

User.all.each do |user|
  user.photo.recreate_versions!
end

你真的把这个包括在你的PhotoUploader课堂上吗?如果是这样,那可能是你的问题。尝试从上传器中删除该代码。现在,打开 rails 控制台(rails console在您的应用程序文件夹中从命令行运行命令)。键入User.first.photo.class。返回值应该是PhotoUploader. 如果是,那么上面的方法也应该有效。将其复制并粘贴到控制台中,让我们知道它是如何进行的。

于 2013-05-25T01:13:51.027 回答
0

Your current issue is that you are expecting photo to be an uploader before it is. You can't call recreate_versions! on it during the class definition of the thing it is going to use as proxy for user.photo.

Once the uploader class is defined during the setup, you can then call user.photo.recreate_versions! assuming you mounted that uploader.

于 2013-05-24T21:33:01.743 回答
0

在用户模型中写

mount_uploader :photo, PhotoUploader
于 2013-05-24T18:56:53.860 回答