I have an image that belongs_to
a user and to a binary (physical file attributes are stored in a separate model). In the old days (read: yesterday), I set the user_id value manually:
@image = Image.new( params[:image] )
@image.user_id = current_user
A friend recently clued me in to the fact that I should use associations instead, so my controller code became:
@image = current_user.image.new( params[:upload] )
That, of course, is much nicer and works great. Now I'd like to do something similar for my binary association, but I don't know how. Extracting and storing my binary is done by a BinaryObserver
class that observes the Image
model. In the observer's before_validation
callback, the uploaded file is sent to the Binary
class and and a binary object is created/stored. Once stored, I need to set the binary_id
value for my image model. I've been doing that the manual way, but I now feel like I should be doing it the other way. Here's what I have in BinaryObserver#before_validation
:
def before_validation( model )
binary = Binary.new.upload( model.upload ) rescue raise
binary = binary.store()
model.binary_id = binary.id
rescue => e
#
# Rethrow any exception that was raised.
#
raise
end
Should I be doing this the other way? If so, how? In a multiple association scenario, I can't see a way to set more than one foreign key value "automagically".
Thanks.
Rob