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

あなたのコードで私が気づいたことの1つは、

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

ユーザーモデルに書く

mount_uploader :photo, PhotoUploader
于 2013-05-24T18:56:53.860 に答える
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 に答える