Carrierwave Rails 3 S3, save the file size to the database

孤人 提交于 2020-01-13 19:55:06

问题


Using Carrierwave with Rails 3.2.6. All fine, except I need to sort a table where some attachments are displayed by file size. I'm using S3 for storage with fog.

Let's say I have a Carrierwave showing like this:

<%= @project.attachment %>

I am able to show the size of the file by using '.size' after the field name:

<%= @project.attachment.size %>

shows the file size in bytes, but as I need to use an order clause when getting the records from the database, I cannot sort on this. Is there any way to write the file size to a particular column in the database after it has been uploaded so I can sort on this??

many thanks


回答1:


this worked for me

 before_save :update_project_attributes

 private

 def update_project_attributes
    if project.present? && project_changed?
      self.file_size = project.file.size
    end
 end



回答2:


You should add a virtual attribute to the model and define a custom getter method that returns the file size. You can then sort with respect to this virtual attribute as you usually would. Let me know if you need more details and I will try to provide them!




回答3:


Ok, got this to work with before_save

before_save :set_size

def set_size
  self.size = self.upload.size
end

where upload is the mounted field and size is a new db column to store the size.



来源:https://stackoverflow.com/questions/11785094/carrierwave-rails-3-s3-save-the-file-size-to-the-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!