خرید بک لینک

Vote count: 0

I am using Carrierwave 0.5.8 for storing uploaded file. In my app users can upload any file. So I have to maintain folders like "public/uploads/1/", "public/uploads/2/", where 1, 2...etc will be user ids, and these folders will contain files uploaded by user in his corresponding id folder.

So I was reading the doc at : Carrierwave github repo and it has some code like :

u = User.new
u.avatar = params[:file] # Assign a file like this, or

# like this
File.open('somewhere') do |f|
   u.avatar = f
end

u.save!

My question is, what is the File.open("Somewhere") ? Where is the second parameter like "r" or "w" ? Isn't it vague for the begier to understand?

"Somewhere" can't be directory because it is "File.open", it will look for the file. If it is a file then what path should I give? I don't know the name of file beforehand. We can get the filename from the file object parama[:file]. Then it means I have to do something like this:

File.open(Rails.root.join('public', 'uploads/', @user.id, filename), "w") do |file|
  u.avatar = file
end
# I am able to achieve with this what I want to do

Right?

That is fine, But there is one another setting/action in file_uploader.rb :

# Override the directory where uploaded files will be stored.
# This is a sensible default for uploaders that are meant to be mounted:

def store_dir
  "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end

So as per the document it will store the files in that particular folder, based on model.id. But then I am confused what I am doing with File.open action?

On top of the documentation there is some more code :

# You can use your uploader class to store and retrieve files like this:
uploader = AvatarUploader.new
uploader.store!(my_file)

I guess store_dir action works with this .store action. But when I use this. The file gets stored in tmp directory in image folder. And view throws an error Called id for nil, model.id something like this from store_div action (Even if it doesn't throw error, it is not saving the file in folder).

Note: I am just using it as leaing purpose.

I am confused with which thing doing what: User.new with file.open or AvatarUploader.new with Uploader.store (Which code when to use and where to use). Can anybody explain?

asked 1 min ago

برچسب: نویسنده: استخدام کار تاريخ: دوشنبه 3 خرداد 1395 ساعت: 21:20

صفحه بندی