ActiveRecord: Can't change the value of self

I have a system where uploads are stored in a database with a filename based on the MD5 hash of the file contents. Following the logic of this, I assigned upload_file_name to be a unique index in my migration.

What I want to do is, whenever a user tries to upload a file whose md5 hash already exists in the database, just redirect to that other record rather than making a copy (which actually just throw an error because upload_file_name is a unique index)

So I put in my model:

self = other_upload if other_upload = Upload.find_by_upload_file_name(self[:upload_file_name])

which ActiveRecord doesn't let me do saying "Can't change the value of self"

Ideas?

That is not an ActiveRecord issue it is a basic Ruby issue. Once you are inside an instance method I do not think there is any way of suddenly deciding you want to be in the method of a different object. You could put something like the above code in a method of the model that, rather than setting self, returns either itself or the alternative, then call that method from the controller.

Colin

thanks for the help.

+1 The functionality you're interested in should be called from the controller.

# pseudo-Ruby upload = Upload.new(params[:upload]) if Upload.find_by_file_name(upload.file_name)   upload = Upload.find_by_file_name(upload.file_name) end

You can't change "self" to "be" a different instance, but you can overwrite a variable containing one instance, with another instance.

I know I have to do it in the controller is just wish there was some way I could put it into the model that way I never have to worry about it in my "skinny controller".

I assume you're replying to my post... but because you cut everything, I don't know for sure...

I know I have to do it in the controller is just wish there was some way I could put it into the model that way I never have to worry about it in my "skinny controller".

find_or_initialize_by_?

Although, if you're doing some fudging with MD5 hashes, you may not be able to use the dynamic methods....

# upload.rb def self.find_or_initialize_by_params(params)   upload = Upload.new(params)   return Upload.find_by_upload_file_name(upload.upload_file_name) || upload end

#controller upload = Upload.find_or_initialize_by_params(params)