Domanda

I'm working on Sinatra site which allows user to upload files. I got this action route:

post '/upload' do
  params.delete 'submit'
  UsrUpld.new(
    :name       => params[:name]
    :created_at => Time.now
  ).save
  params[:photos].each do |photo|
    File.open('public/uploads/' + UsrUpld.id + '/' + photo[:filename], 'w') do |file|
      file.write(photo[:tempfile].read)
    end
  end
  redirect '/index'
end

I think this should create document in MongoDB with two fields name and created_at, the take file from POST request and write it in public/uploads/ID/FILE.jpg. But Pow returns me undefined method `id' for UsrUpld:Class. How to ask object's id in route with Mongoid?

Thank you in advance.

È stato utile?

Soluzione

To ask an id, object should placed in variable which should contain exactly this object, so code should look like this:

post '/upload' do
  params.delete 'submit'
  u = UsrUpld.new(
    :name       => params[:name],
    :created_at => Time.now
  )
  u.save
  params[:photos].each do |photo|
    unless File.exists?('public/media/' + u.id)
      Dir.mkdir('public/media/' + u.id)
    end
    File.open('public/uploads/' + u.id + '/' + photo[:filename], 'w') do |file|
      file.write(photo[:tempfile].read)
    end
  end
  redirect '/index'
end

Also dir should exist before opening the file, thats why Dir.mkdir line added.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top