I have a controller which has two methods: upload and submit
I can ensure that the upload method is executed before submit is called.
in the upload, I have such code:
def upload
@file = params[:avatar]
...
end
in the submit, I have such code:
def submit
...
user.avatar = @file
...
end
but it seems that the @file is nil.
Where am I wrong?….
I’m using Rails 3.2.0
Instance variables in controllers do not persist between requests. Every request creates a new instance of the controller class so the
@fileyou save inuploadgoes away whenuploadfinishes. Then, when a new request comes in that is routed to yoursubmitmethod, Rails will create a new instance of your controller class and callsubmiton it. Since you have two instances of the class, you have two sets of instance variables and they won’t share your@file.You have to arrange for the
@fileto be stored in your database, session, form, etc. between requests and then yoursubmithas to load it from where ever it is stored and assign it touser.avatar.