I’m creating an image file upload service for my web site.
As well as saving the actual file I also need to create a database
record for the file.
I would like to name the file after the record id, but I also need to
save some attributes of the image (width/height/mime_type etc) which I
can’t discover until after the file is created.
- The id is not available until after the record is saved so I can’t
create the file until after the record has been created
Yes, that’s correct that the id of the record isn’t known until it is
- if I try to update the record in the after_create hook it creates an
extra record in the database instead of updating the existing one.
I think that you would want to use the after_save hook instead of the
after_create if you’re wanting to perform an update of the file’s meta-
data. However, you may also want to take a look at the before_save
callback as well in the api.rubyonrails.com.
Is this a bug?
Where’s the code snippet? Are you trying to store the file into the
database or simply create metadata for the file that’s stored into the
Any advice to resolve this problem would be most welcome.
It could be done in the controller of course, but I feel it belongs in
Lastly, most of the database reading/writing can be isolated into the
class model and this is the recommended pattern to follow when it’s
possible. However, you should understand the controller’s role in the
MVC design pattern. It’s job is to act as the mediator between the
model and the view. Thus, the controller may make decisions to
create, read, update, and delete (CRUD) a model instance or models
depending on what action is invoked on the controller.