carrierwave cache images and activerecord - ruby-on-rails-3

I am using Rails 3 and carrierwave gem.
My problem is the next:
I am coding a wizard form with multiple models and relations. So My application has products which has many images through Image model (Its has been mounted with carrierwave).
Because the form has many steps I want save temporaly the images with cache option in CarrierWave. then i last step i want recover the images and load my product. So I create a model called TempData which save temporaly data (In this case cache_name), a type_identifier and a mark can_be_deleted.
For example these are my models:
Product Model:
class Product < ActiveRecord::Base
has_many :images, :as => :imageable, :dependent => :destroy
def save_images_in_temporal_folder(images_attributes)
begin
uploader = ImageUploader.new
images_attributes.to_hash.each do |image|
uploader.cache!(image[1]['filename'])
TempData.create(:data => uploader.cache_name, :can_deleted => false, :type_name => TempDataType.product_image_upload_to_words)
end
rescue
end
end
def load_images_from_temporal_folder
begin
uploader = ImageUploader.new
tmp_images = []
TempData.find_all_by_can_deleted_and_type_name(false, TempDataType.product_image_upload_to_words).map(&:data).each do |cache_name|
tmp_images << uploader.retrieve_from_cache!(cache_name)
end
tmp_images
rescue
end
end
end
Image model
class Image < ActiveRecord::Base
attr_accessible :imageable_type, :imageable_id, :filename
belongs_to :imageable, :polymorphic => true
mount_uploader :filename, ImageUploader
#validates :filename, :presence => true
end
My ImageUploader:
class ImageUploader < CarrierWave::Uploader::Base
configure do |config|
config.remove_previously_stored_files_after_update = false
end
include CarrierWave::RMagick
storage :file
def store_dir
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
def self.store_dir_for_file(model, mounted, filename, version = "")
filename = "#{version}_#{filename}" unless version.blank?
"uploads/#{model.class.to_s.underscore}/#{mounted}/#{model.id}/#{filename}"
end
process :resize_to_limit => [200, 300]
version :thumb do
process :resize_to_limit => [50, 50]
end
version :big do
process :resize_to_limit => [400, 400]
end
def extension_white_list
%w(jpg jpeg gif png)
end
end
So How i save/cache the images with model and mount information?. How retrieve the cache and load my product with images in cache?
Thanks in advance. Sorry for my english and if you need more information comment this post.

View the next link:
CarrierWave with ActiveResource
Also I create a model which storage temporal data. Here I save the cache_name of carrierwave. When i save the product mark these register as can_be_deleted. Then I write a task which delete these registers and clean Carrierwave cache files.

Related

Browse button is not working for carrierwave and uplodify

Hi I am uploading the video from my rails app.
For this I am using carrierwave gem.
I am referring this tutorial for it.
But when I tried to upload the video from my computer by using Browse button it is not allowing me to browse.
When I checked in the firebug I have getting this type of error
"NetworkError: 404 Not Found - http://localhost:3000/videos/uploadify.swf?preventswfcaching=1393936089114"
I tried to solve it but I didn't get any solution for it.
Here is my
videos controller
class VideosController < ApplicationController
def index
end
def show
#video = Video.find(params[:id])
end
def new
#video = Video.new(video_params)
end
def create
#video = Video.new(video_params)
if #video.save
render :nothing => true
else
render :nothing => true, :status => 400
end
end
private
def video_params
params.require(:video).permit(:attachment, :zencoder_output_id, :processed, :video, :meta_info) if params[:gallery]
end
end
model - video.rb
class Video < ActiveRecord::Base
belongs_to :gallery
mount_uploader :video, VideoUploader
end
uploader file
class VideoUploader < CarrierWave::Uploader::Base
include CarrierWave::Video
storage :file
def store_dir
"videos/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
process encode_video: [:mp4, resolution: "200x200"]
def extension_white_list
%w(avi mov mkv mpg mpeg mp4 m4v flv)
end
end
I am using rails 4 and ruby 2.1.0

Issues with validation using carrierwave gem in rails 3

Hey so this is really bugging me. I've implemented Carrierwave into my app with a simple image upload. Im trying to validate the image to be the correct filetype and I'm getting a few strange results. Heres the relevant code:
class Art < ActiveRecord::Base
belongs_to :collection
attr_accessible :image, :collection_id, :remote_image_url
mount_uploader :image, ImageUploader
validates_integrity_of :image
validates_presence_of :image
validates_processing_of :image
end
class ImageUploader < CarrierWave::Uploader::Base
include CarrierWave::MiniMagick
storage :file
def store_dir
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
def extension_white_list
%w(jpg jpeg gif)
end
class ArtsController < ApplicationController
def new
#art = Art.new(:collection_id => params[:collection_id])
end
def edit
#art = Art.find(params[:id])
end
def create
#art = Art.new(params[:art])
if #art.save
flash[:notice] = "Successfully created art."
redirect_to #art.collection
else
flash[:error] = #art.errors
render :action => :new
end
end
def update
#art = Art.find(params[:id])
if #art.update_attributes(params[:art])
flash[:notice] = "Successfully updated art."
redirect_to #art.collection
else
flash[:error] = #art.errors
render :action => :edit
end
end
def destroy
#art = Art.find(params[:id])
#art.destroy
flash[:notice] = "Successfully destroyed art."
redirect_to #art.collection
end
end
en:
errors:
messages:
carrierwave_processing_error: "Cannot resize image."
carrierwave_integrity_error: "Not an image."
carrierwave_download_error: "Couldn't download image."
extension_white_list_error: "NOT ALLOWED"
extension_black_list_error: "You are not allowed to upload %{extension} files,
prohibited types: %{prohibited_types}"
So when i create a new piece of art with a png file format an error will occur that the image cannot be blank. I understand this is the validates_presence_of being trigger but i am supplying it with something just not the correct format. If i remove the validates_presence_of non correct file formats won't display but will still be created. I also assed the i18n error messages to my en.yml file. I'm somewhat new to rails so i assume there is an issue in my controller with creating each piece of art but im not sure what I'm doing wrong.

Rails How To Manually Create Child Object Without Form

I was wondering what the best implementation would be to programatically generate a single child object for a parent(s) without the use of a form.
In my case I have an existing forum system that I would like to tie into my Upload system via comments. I would like to manually create a child Forum object to discuss said upload in the same create action that the Upload is created. The two models have a relationship as so:
Child forum:
class Forum < ActiveRecord::Base
...
belongs_to :upload
end
Parent upload:
class Upload < ActiveRecord::Base
...
has_one :forum
end
I was thinking of something along the lines of:
class UploadsController < ApplicationController
...
def create
#Create the upload and a new forum + initial post to discuss the upload
#upload = Upload.new(params[:upload])
#forum = Forum.new(:upload_id => #upload.id, :title => #upload.name...)
#first_post = Post.new(:forum_id => #forum.id....)
if #upload.save && #topic.save && #first_post.save
redirect_to :action => "show", :id => #upload.id
else
redirect_to :action => "new"
end
end
end
Which is fairly close to what I wanted to do but the parent ids aren't generated until the parent objects are saved. I could probably do something like:
#upload.save
#forum = Forum.new(:upload_id => #upload.id...
#forum.save....
But I thought it might be cleaner to only persist the objects if they all validated. I'm not sure, does anybody else know of a better implementation?
I would recommend moving the forum creation from the controller to the model. The forum will only be created on the successful creation of the Upload.
class Upload < ActiveRecord::Base
...
has_one :forum
after_create :create_forum
...
def create_forum
Forum.create(:upload_id => self.id, :title => self.name...)
end
end
class Forum < ActiveRecord::Base
...
has_many :posts
after_create :create_first_post
...
def create_first_post
Post.new(:forum_id => self.id)
# or self.posts << Post.new()
end
end

How to reassign uploaded files to some other models rails 3.1

I have a scenario where i am uploading files dynamically using ajax remotipart, then later i assign those uploaded files to any model. I have such settings in uploader.
class DocumentUploader < CarrierWave::Uploader::Base
storage :file
def store_dir
"uploads/#{model.class.to_s.pluralize.underscore}/#{model.documentable_type.to_s.pluralize.underscore}/#{model.documentable_id}"
end
def extension_white_list
%w(doc pdf docx xls xlsx)
end
end
class Document < ActiveRecord::Base
mount_uploader :document, DocumentUploader
belongs_to :documentable, :polymorphic => true
validates :document, :presence => true
validates :description, :presence => true
end
class Post < ActiveRecord::Base
has_many :documents, :as=>:documentable
end
When i upload a document without providing documentable source, it uploads the files to /uploads/documents/uploaded_file.doc
But when i assign that document to some other model like
#post = Post.first
#post.documents << Document.last
#post.save
It save the record correctly and when get url of the file like #post.documents.first.document.url it gave url like this /uploads/documents/posts/10212/uploaded_file.doc where the file was not available.
How can i handle such assignment of pre-existing uploads?
I came here while googling and thought some people might help this piece of code I'm using in a controller to re-assign a file (here it's an image) to another model which is handled with CarrierWave:
def create
temporary_image = TemporaryImage.find(params[:temporary_image][:id])
#player = Player.new(params[:player])
#player.image = File.open(temporary_image.image.current_path)
# now you can handle #player.image as if it was
# originally assigned by CarrierWave
end
where
class Player < ActiveRecord::Base
attr_accessible :image
mount_uploader :image, PlayerImageUploader
end
and
class TemporaryImage < ActiveRecord::Base
attr_accessible :image
mount_uploader :image, TemporaryImageUploader
end
I'm using this in conjunction with an ajax fileupload (stored via TemporaryImage) where the image is immediately presented and can then be cropped. After cropping it is stored within Player.
I solved the issue by doing lot of hit and trail. but finally solved.
class Document < ActiveRecord::Base
mount_uploader :document, DocumentUploader
belongs_to :documentable, :polymorphic => true
validates :document, :presence => true
validates :description, :presence => true
after_update :relocate_files
def relocate_files
src_file = Rails.root.join("public", "uploads", "documents", document.url.split("/").last)
dst_file = Rails.root.join("public", "uploads", "documents", documentable_type.pluralize.underscore, documentable_id.to_s, document.url.split("/").last)
unless FileTest.exists?(dst_file)
FileUtils.mkdir_p(File.dirname(dst_file))
FileUtils.mv(src_file, dst_file)
end
end
end

Resize original image in Paperclip

Paperclip stores original images in "original" folder. Is there a way to resize the original images? I want to make the originals smaller in order to save the disc space.
So, for example, if visitor uploads a photo with 2592x1936 I want to store it as 1024x1024, the same way we set the dimensions for :thumb images in :styles
Update (solved)
I found out how to resize original images automatically on upload. One just needs to add :original to styles:
class MyModel < ActiveRecord::Base
has_attached_file :photo,
:styles => { :original => "1024x1024>", :thumb => "150x150>" }
end
I'm not sure paperclip does resizing by itself. You might have to look at Rmagick to get this done. I would try to get RMagick going (or minimagick) and then use a before_save callback to execute a :resize method that you write that tells RMagic to resize the image. Your method might look like:
class Image < ActiveRecord::Base
belongs_to :profile
before_save :resize
def resize
self.image = self.image.resize "1024x1024"
end
end
or
class Image < ActiveRecord::Base
belongs_to :profile
before_save do
self.image = self.image.resize "1024x1024"
end
end