I cannot find any documentation on this sort of thing.
It seems like an unsaved object does not have an ID when it is built;
but at some point between when it is created and saved it gains one.
Associations don’t work properly until it has one. My Upload object
doesn’t know which Comment object it belongs to until Comment has an ID
number; and again, I don’t want to save EITHER object until BOTH are
validated, which has led to a headache indeed.
I cannot reference an associated comment from my Upload model within the
before_validation_on_create method, but I CAN do so within the
before_create method. Right now I have something sort-of-working. What
I have is like this. I have changed my forms so that my file field is
comment[upload] instead of upload[upload]:
class Comment < ActiveRecord::Base
belongs_to :board
has_many :uploads, :dependent => :destroy
acts_as_tree :order => “created_on ASC”, :dependent =>
:destroy
validates_associated :uploads
def upload=(upload)
uploads.build({:upload => upload}) if upload.size > 0
end
end
That catches the uploaded file and sends it to the Upload model ->
class Upload < ActiveRecord::Base
belongs_to :comment
def upload=(upload)
@upload = upload
end
def before_validation_on_create
create_image
end
def create_image
#this is some RMagick nonsese.
end
def before_create
@thumbnail = ImageList.new.from_blob(@image.first.to_blob)
if !comment.parent_id
x = comment.board.setting(:parent_thumbnail_at_width)
y = comment.board.setting(:parent_thumbnail_at_height)
else
x = comment.board.setting(:reply_thumbnail_at_width)
y = comment.board.setting(:reply_thumbnail_at_height)
end
self[:thumbnail_width] = @thumbnail.columns
self[:thumbnail_height] = @thumbnail.rows
if @thumbnail.columns > x or @thumbnail.rows > y
@thumbnail.change_geometry!("#{x}x#{y}") {|cols, rows, img|
img.resize!(cols, rows)}
end
end
end
As you can see, it was imortant that I could reference the associated
comment, because that determined the size of the thumbnail, which I
needed to save to the uploads table.
So I’m closer than when I was before; but still have a long way to go.
For example, I’m only dealing with one uploaded file at a time, when I
need to be dealing with multiple uploads