Rails 3 Custom Class Question
I am trying to create a separate model class for image uploading, which was previously in the object's controller. I also want to make it agnostic, so I can upload images using one class from multiple objects.
In my original object's model class, I have the following now:
class Object < ActiveRecord::Base
after_save :photo_store
delegate :has_photo?, :photo, :photo_path, :store_photo, :photo_filename, :to => :photo_store
def photo_store
PhotoStore.new(self)
end
end
Then, the PhotoStore class looks like this:
class PhotoStore
attr_reader :object
def initialize(object)
@object = object
end
def photo=(file_data)
unless file_data.blank?
@file_data = file_data
self.extension = file_data.original_filename.split('.').last.downcase
end
end
PHOTO_STORE = File.join RAILS_ROOT, 'public', 'photo_store'
def photo_filename
File.join PHOTO_STORE, "#{id}.#{extension}"
end
def photo_path
"/photo_store/#{id}.#{extension}"
end
def has_photo?
File.exists? photo_filename
end
private
def store_photo
if @file_data
FileUtils.mkdir_p PHOTO_STORE
File.open(photo_filename, 'wb') do |f|
f.write(@file_data.read)
end
end
end
end
However, this throws the error below when I try and use the has_photo? method in the object's view.
undefined local variable or method `id' for #
Do I need to put some other type of relationship in place between the Object and PhotoStore?
And a separate question: What's the best way to make this agnostic? Since it uses just the ID of the object, I could just include the Object's name in the filename, but is th开发者_开发技巧at the best way to do it?
Thanks!
Because at File.join PHOTO_STORE, "#{id}.#{extension}"
you call method PhotoStore#id
, but it does not exists.
You should do that
File.join PHOTO_STORE, "#{@object.id}.#{@object.extension}"
精彩评论