views:

32

answers:

2

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

A: 

I think I figured out the right answer. Instead of setting a variable to hold the newly created Binary instance, I set the association itself:

model.binary = Binary.new.upload( model.upload ) rescue raise

That seems to do exactly what I was after. It sets the foreign key value automatically and also allows me to being acting on the associated object directly.

Rob Wilkerson
A: 

Do you also have a has_one/belongs_to relationship for Image/Binary? That might be of use as well...

Shane Liebling
I do. An Image belongs_to a Binary and a Binary has_one Image.
Rob Wilkerson