media = Media.new(params[:media])
media.save
@attachment.me开发者_Python百科dia = Media.find(????)
@attachment.save
I tried just doing media.id
but apparently, that is the media that hasn't been saved to the db yet.... so how do I get the ID?
If media.id
is not assigned, you probably had an error when saving and media.save
returned false
, though since you don't check for it you didn't notice.
The way to avoid this is to request the stricter save:
def something
media = Media.new(params[:media])
media.save!
rescue ActiveRecord::RecordInvalid
# Something couldn't be saved
render(...)
end
Generally if a record saves correctly, then media.errors.full_messages
will be an empty array.
If there are no errors, then it is possible that one of your before_
or after_
filters returned false and prevented it from being saved, though this is less common.
Why not just do the following?
media = Media.new(params[:media])
media.save
@attachment.media = media
@attachment.save
Why not use the build_xxx methods you get via the association?
@attachment.build_media(params[:media])
@attachment.save
I suppose this media object is not valid, thus has not been saved.
If it would be saved, you would have media.id already set.
精彩评论