Rails 4 - Paperclip is not uploading files - ruby-on-rails

I am testing an Rails 4 application in localhost which uses Paperclip, and even though submitting images creates entries in the Database, the images folder is always empty.
Model
class Tile < ActiveRecord::Base
belongs_to :game
# Paperclip
has_attached_file :image,
styles: { medium: "300x300>", thumb: "100x100>" },
url: "/images/:style/:filename",
default_url: "/images/:style/missing.png"
validates_attachment_content_type :image, content_type: /\Aimage\/.*\Z/
end
Controller
class TilesController < ApplicationController
before_action :set_game
def create
tile = #game.tiles.create tile_params
redirect_to #game, notice: tile
end
private
# Use callbacks to share common setup or constraints between actions.
def set_game
#game = Game.find(params[:game_id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def tile_params
params.require(:tile).permit(:image)
end
end
View form
<%= form_for([#game, Tile.new], multipart: true) do |form| %>
<%= form.file_field :image %>
<% end %>
Everytime I try to print <p><%= tile.image.url %></p> I get /images/original/missing.png.
Why is this?
Update
I am using Ubuntu 14.04.
Imagemagick is installed.

Be sure to also update path long with url, ie
has_attached_file :image,
styles: { medium: "300x300>", thumb: "100x100>" },
path: "/images/:style/:filename",
url: "/images/:style/:filename",
default_url: "/images/:style/missing.png"
As explained in this Railscasts ~5:20, url sets where images will be retrieved from, and path sets where they will be stored.

Assuming you're using window, to show image on the screen: image_tag(tile.image.url(:small))
Also, did you install ImageMagick and file for Windown?'
and if yes, did you set your environment to: Paperclip.options[:command_path] = 'C:\Program Files (x86)\GnuWin32\bin' in the config/environments/development.rb? then restart your server.

Related

Why image_tag doesn't show image while link_to shows?

I want to display image in my cart via paperclip gem but it won't works with image_tag while with link_to work fine
This works:
<% simple_current_order.line_items.all.each do |line_item| %>
<%= link_to mini_image(line_item.variant)), product_path(line_item) %>
<% end %>
While this not
<% simple_current_order.line_items.all.each do |line_item| %>
<%= image_tag mini_image(line_item.variant) %>
<% end %>
image.rb model
module Spree
class Image < Asset
validate :no_attachment_errors
has_attached_file :attachment,
styles: { mini: '48x48>', small: '100x100>', product: '240x240>', large: '600x600>' },
default_style: :product,
url: '/spree/products/:id/:style/:basename.:extension',
path: ':rails_root/public/spree/products/:id/:style/:basename.:extension',
convert_options: { all: '-strip -auto-orient -colorspace sRGB' }
validates_attachment :attachment,
:presence => true,
:content_type => { :content_type => %w(image/jpeg image/jpg image/png image/gif) }
# save the w,h of the original image (from which others can be calculated)
# we need to look at the write-queue for images which have not been saved yet
after_post_process :find_dimensions
#used by admin products autocomplete
def mini_url
attachment.url(:mini, false)
end
def find_dimensions
temporary = attachment.queued_for_write[:original]
filename = temporary.path unless temporary.nil?
filename = attachment.path if filename.blank?
geometry = Paperclip::Geometry.from_file(filename)
self.attachment_width = geometry.width
self.attachment_height = geometry.height
end
# if there are errors from the plugin, then add a more meaningful message
def no_attachment_errors
unless attachment.errors.empty?
# uncomment this to get rid of the less-than-useful interim messages
# errors.clear
errors.add :attachment, "Paperclip returned errors for file '#{attachment_file_name}' - check ImageMagick installation or image source file."
false
end
end
end
end
It can't find image with image tag, anyone know why?

validates_attachment_content_type isn't accepting .tmTheme files (Sublime Text color schemes)

I'm attempting to use a form to upload and store Sublime Text themes in a database.
It works fine with images, but replacing the content_type with the one applicable to Sublime Text theme files consistently tells me that the file "has contents that are not what they are reported to be"
class Color < ActiveRecord::Base
has_attached_file :file
validates_attachment_content_type :file, :content_type => ["image/png"]
end
Works fine
class Color < ActiveRecord::Base
has_attached_file :file
validates_attachment_content_type :file, :content_type => ["application/xml"]
end
Does not
I think you might need to tell Paperclip (I'm assuming that's what you are using) that 'tmtheme' is a valid extension by adding this to your config/environments/development.rb and config/environments/production.rb:
Paperclip.options[:content_type_mappings] = {
:tmtheme => "application/xml"
}

Paperclip Upload to S3 with Delayed Job

I am trying to upload a file to s3 in background using Rails (4.2) with delayed_job gem.
My code is basically what is shown in this post:http://airbladesoftware.com/notes/asynchronous-s3/ (with small changes).
The Photo Modal
class Photo < ActiveRecord::Base
belongs_to :gallery
has_attached_file :local_photo,
path: ":rails_root/public/system/:attachment/:id/:style/:basename.:extension",
url: "/system/:attachment/:id/:style/:basename.:extension"
has_attached_file :image,
styles: {large: '500x500#', medium: '180x180#'},
storage: :s3,
s3_credentials: lambda { |attachment| attachment.instance.s3_keys },
s3_permissions: :private,
s3_host_name: 's3-sa-east-1.amazonaws.com',
s3_headers: {'Expires' => 1.year.from_now.httpdate,
'Content-Disposition' => 'attachment'},
path: "images/:id/:style/:filename"
validates_attachment_content_type :image,
content_type: [
"image/jpg",
"image/jpeg",
"image/png"]
def s3_keys
{
access_key_id: SECRET["key_id"],
secret_access_key: SECRET["access_key"],
bucket: SECRET["bucket"]
}
end
after_save :queue_upload_to_s3
def queue_upload_to_s3
Delayed::Job.enqueue ImageJob.new(id) if local_photo? && local_photo_updated_at_changed?
end
def upload_to_s3
self.image = Paperclip.io_adapters.for(local_photo)
save!
end
end
class ImageJob < Struct.new(:image_id)
def perform
image = Photo.find(image_id)
image.upload_to_s3
image.local_photo.destroy
end
end
With this code, the job (ImageJob) run in background (I can see it on delayed_job_web), no error. But the file is not uploaded.
If I "disable background" and use only:
ImageJob.new(id).perform if local_photo? && local_photo_updated_at_changed?
The file is uploaded to the amazon and local file is deleted too.
Any suggestions ?
Thanks in advance
UPDATE #1 Now I can see the error:
Job failed to load: undefined class/module ImageJob. Handler: "--- !ruby/struct:ImageJob\nimage_id: 412\n"
UPDATE #2 I make this working using delay method, something like this:
def perform
if local_photo? && local_photo_updated_at_changed?
self.delay.move_to_s3
end
end

Getting correct path/url from Paperclip Gem during after_post_process callback?

I have a fairly standard Paperclip setup, it's almost straight out of the readme. I have a simple method triggered via callback to get the primary colors out of an uploaded image, and save them to the corresponding instance.
class Image < ActiveRecord::Base
has_attached_file :file, :styles => { large: "800x>", :medium => "300x300>", :thumb => "100x100>" }, :default_url => "/images/:style/missing.png"
validates_attachment_content_type :file, :content_type => /\Aimage\/.*\Z/
after_post_process :get_colors
def get_colors
colors = Miro::DominantColors.new(self.file.url)
colors = colors.to_hex.join(',')
self.colors = colors
self.save
end
end
As you can see, I have an after_post_process callback, and it does get triggered. The trouble is that when I call self.file.url I get a path that looks like this:
"/system/images/files//original/Peterson-Products-Wireframe-v01.jpg?1398443345".
It's missing the :id_partion portion. It's real path should look more like:
"/system/images/files/000/000/033/original/Peterson-Products-Wireframe-v01.jpg?1398443345"
Should I be using some other callback? I only want this triggered once per upload... Never again if the image is updated. Is this a bug in paperclip that I should be filing on Github?
Rails Version 4.1
Paperclip Version 4.1
Ruby 2.1.0
Thanks so much!
try queued_for_write
colors = Miro::DominantColors.new(file.queued_for_write[:original].path)

no validates_attachment_file_name when upgrading to Paperclip 4.1 from 3.5

We have code that looks like run of the mill paper clip:
has_merchants_attached_file :pdf,
storage: :s3,
s3_credentials: Mbc::DataStore.s3_credentials,
s3_permissions: :private,
path: ":identifier_template.pdf",
bucket: Mbc::DataStore.forms_and_templates_bucket_name
validates_attachment_file_name :pdf, :matches => [/pdf\Z/]
Which generates an error:
undefined method `validates_attachment_file_name' for #<Class:0x007fba67d25fe0>
Interestingly enough, when we down grade back to 3.5, we encounter the same issue.
The controller that is generating this is:
def index
#fidelity_templates = FidelityTemplate.order("identifier asc").all
end
Additionally:
def has_merchants_attached_file(attribute, options={})
if Rails.env.test? || Rails.env.development?
has_attached_file attribute,
path: "paperclip_attachments/#{options[:path]}"
else
has_attached_file attribute, options
end
end
Any thoughts on what could be causing this?
You can read about the provided validators here:
https://github.com/thoughtbot/paperclip#validations
The included validators are:
AttachmentContentTypeValidator
AttachmentPresenceValidator
AttachmentSizeValidator
They can be used in either of these ways:
# New style:
validates_with AttachmentPresenceValidator, :attributes => :avatar
# Old style:
validates_attachment_presence :avatar
UPDATE ...
If you read further down the link I've given above you'll get to a section on Security Validations (Thanks Kirti Thorat):
https://github.com/thoughtbot/paperclip#security-validations
They give an example on how to validate the filename format:
# Validate filename
validates_attachment_file_name :avatar, :matches => [/png\Z/, /jpe?g\Z/]
From your code snippet it looks like your validation should work as-is.
However, I've never seen paperclip used with this syntax:
has_merchants_attached_file ...
Perhaps that's the source of your issues? You would usually use the following to attach files to your model:
has_attached_file :pdf ...

Resources