I am using Asset and sub-Asset models as models to hold images. I have Product model that has many assets, but uploading an image fails at the build process right before saving Product model.
Product Model
class Product < ActiveRecord::Base
has_one :pic, :as => :assetable, :class_name => "Pics::Product", :dependent => :destroy
Asset Model
class Asset < ActiveRecord::Base
belongs_to :assetable, :polymorphic => true
attr_accessible :assetable_id, :assetable_type, :attachment, :type
end
Pics::Product Model (sub-Asset model)
class Pics::Product < Asset
has_attached_file :attachment,
:styles => { :large => "500x500>",
:medium => "190>x",
:small => "115x115>" },
:default_url => 'missing-product-:style.png'
attr_accessible :attachment
end
Products#Create
class ProductsController < ApplicationController
before_filter :authenticate_user!
def create
#product = Product.new(params[:product])
puts "=========="
ap #product.pic
#product.build_pic
puts "=========="
ap #product.pic
if #product.save
render json: #product
else
render json: {:error => "Error in creating a product!"}, :status => :unprocessable_entity
end
end
I printed out #product.pic before and after #product.build_pic. It looks like it was doing the right thing before #product.build_pic is called and then it gets removed after it's called. There is no specific error, so I don't really know why this is happening.....
Output of Products#Create
==========
#<Pics::Product:0x007fd9a3350b40> {
:id => nil,
:type => "Pics::Product",
:assetable_id => nil,
:assetable_type => "Product",
:attachment_file_name => "25-years-of-storage.jpg",
:attachment_content_type => "image/jpeg",
:attachment_file_size => 753780,
:attachment_updated_at => Sat, 22 Dec 2012 00:13:22 UTC +00:00,
:created_at => nil,
:updated_at => nil
}
===========
#<Pics::Product:0x007fd9a7184da8> {
:id => nil,
:type => "Pics::Product",
:assetable_id => nil,
:assetable_type => "Product",
:attachment_file_name => nil,
:attachment_content_type => nil,
:attachment_file_size => nil,
:attachment_updated_at => nil,
:created_at => nil,
:updated_at => nil
}
Started POST "/products" for 127.0.0.1 at 2012-12-21 16:13:22 -0800
Processing by ProductsController#create as */*
Parameters: {"product"=>{"name"=>"asdfasdfa", "description"=>"asdfasdf", "child_id"=>"1", "pic_attributes"=>{"attachment"=>#<ActionDispatch::Http::UploadedFile:0x007fd9a61a4dc0 #original_filename="25-years-of-storage.jpg", #content_type="image/jpeg", #headers="Content-Disposition: form-data; name=\"product[pic_attributes][attachment]\"; filename=\"25-years-of-storage.jpg\"\r\nContent-Type: image/jpeg\r\n", #tempfile=#<File:/var/folders/nm/gj73lnln3c57813fmlm_cxxr0000gn/T/RackMultipart20121221-29846-xhrk9k>>}, "category_id"=>"1", "target_age_min"=>"1", "target_age_max"=>"2", "purchase_date"=>"2012-12-02"}}
User Load (1.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = 1 LIMIT 1
Command :: identify -format %wx%h '/var/folders/nm/gj73lnln3c57813fmlm_cxxr0000gn/T/25-years-of-storage20121221-29846-16vdudk.jpg[0]'
Command :: identify -format %m '/var/folders/nm/gj73lnln3c57813fmlm_cxxr0000gn/T/25-years-of-storage20121221-29846-16vdudk.jpg[0]'
Command :: identify -format %m '/var/folders/nm/gj73lnln3c57813fmlm_cxxr0000gn/T/25-years-of-storage20121221-29846-16vdudk.jpg[0]'
Command :: convert '/var/folders/nm/gj73lnln3c57813fmlm_cxxr0000gn/T/25-years-of-storage20121221-29846-16vdudk.jpg[0]' -auto-orient -resize "500x500>" '/var/folders/nm/gj73lnln3c57813fmlm_cxxr0000gn/T/25-years-of-storage20121221-29846-16vdudk20121221-29846-a234mw'
Command :: file -b --mime '/var/folders/nm/gj73lnln3c57813fmlm_cxxr0000gn/T/25-years-of-storage20121221-29846-16vdudk20121221-29846-a234mw'
Command :: identify -format %wx%h '/var/folders/nm/gj73lnln3c57813fmlm_cxxr0000gn/T/25-years-of-storage20121221-29846-16vdudk.jpg[0]'
Command :: identify -format %m '/var/folders/nm/gj73lnln3c57813fmlm_cxxr0000gn/T/25-years-of-storage20121221-29846-16vdudk.jpg[0]'
Command :: identify -format %m '/var/folders/nm/gj73lnln3c57813fmlm_cxxr0000gn/T/25-years-of-storage20121221-29846-16vdudk.jpg[0]'
Command :: convert '/var/folders/nm/gj73lnln3c57813fmlm_cxxr0000gn/T/25-years-of-storage20121221-29846-16vdudk.jpg[0]' -auto-orient -resize "190>" '/var/folders/nm/gj73lnln3c57813fmlm_cxxr0000gn/T/25-years-of-storage20121221-29846-16vdudk20121221-29846-chaypg'
Command :: file -b --mime '/var/folders/nm/gj73lnln3c57813fmlm_cxxr0000gn/T/25-years-of-storage20121221-29846-16vdudk20121221-29846-chaypg'
Command :: identify -format %wx%h '/var/folders/nm/gj73lnln3c57813fmlm_cxxr0000gn/T/25-years-of-storage20121221-29846-16vdudk.jpg[0]'
Command :: identify -format %m '/var/folders/nm/gj73lnln3c57813fmlm_cxxr0000gn/T/25-years-of-storage20121221-29846-16vdudk.jpg[0]'
Command :: identify -format %m '/var/folders/nm/gj73lnln3c57813fmlm_cxxr0000gn/T/25-years-of-storage20121221-29846-16vdudk.jpg[0]'
Command :: convert '/var/folders/nm/gj73lnln3c57813fmlm_cxxr0000gn/T/25-years-of-storage20121221-29846-16vdudk.jpg[0]' -auto-orient -resize "115x115>" '/var/folders/nm/gj73lnln3c57813fmlm_cxxr0000gn/T/25-years-of-storage20121221-29846-16vdudk20121221-29846-vecmvv'
Command :: file -b --mime '/var/folders/nm/gj73lnln3c57813fmlm_cxxr0000gn/T/25-years-of-storage20121221-29846-16vdudk20121221-29846-vecmvv'
(0.2ms) BEGIN
(0.2ms) COMMIT
(0.2ms) BEGIN
[paperclip] Scheduling attachments for deletion.
[paperclip] Deleting attachments.
(0.2ms) COMMIT
(0.2ms) BEGIN
SQL (0.8ms) INSERT INTO "products" ("category_id", "child_id", "created_at", "description", "name", "purchase_date", "target_age_max", "target_age_min", "updated_at") VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) RETURNING "id" [["category_id", 1], ["child_id", 1], ["created_at", Sat, 22 Dec 2012 00:13:25 UTC +00:00], ["description", "asdfasdf"], ["name", "asdfasdfa"], ["purchase_date", Sun, 02 Dec 2012 00:00:00 UTC +00:00], ["target_age_max", 2], ["target_age_min", 1], ["updated_at", Sat, 22 Dec 2012 00:13:25 UTC +00:00]]
SQL (0.7ms) INSERT INTO "assets" ("assetable_id", "assetable_type", "attachment_content_type", "attachment_file_name", "attachment_file_size", "attachment_updated_at", "created_at", "type", "updated_at") VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) RETURNING "id" [["assetable_id", 16], ["assetable_type", "Product"], ["attachment_content_type", nil], ["attachment_file_name", nil], ["attachment_file_size", nil], ["attachment_updated_at", nil], ["created_at", Sat, 22 Dec 2012 00:13:25 UTC +00:00], ["type", "Pics::Product"], ["updated_at", Sat, 22 Dec 2012 00:13:25 UTC +00:00]]
[paperclip] Saving attachments.
(0.5ms) COMMIT
Completed 200 OK in 3320ms (Views: 1.0ms | ActiveRecord: 9.9ms)
Um.... I just solved my own problem. Instead of calling new and build the accepted attributes, calling create just worked (#product = Product.create(params[:product])).
The problem is I don't know why! :(
Related
I'm currently trying to create an Order instance. There is an association of the model Order with Items. The association is as follows. Order has many Items. I try following the documentation https://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html
class Order < ApplicationRecord
has_many :items
accepts_nested_attributes_for :items
end
class OrdersController < ApplicationController
##
private
def order_params
params.require(:order).permit(:description,
items_attributes: [:id, :quantity])
end
end
From the following post, it shows that the id has to be pass in the params. Rails 5 Api create new object from json with nested resource
params = {order: {description: "this is a test"}, items_attributes: [{id: 3, quantity: 3, description: 'within order -> item'}]}
=> {:order=>{:description=>"this is a test"}, :items_attributes=>[{:id=>3, :quantity=>3, :description=>"within order -> item"}]}
[7] pry(main)> order_test = Order.create!(params[:order])
(0.4ms) BEGIN
Order Create (62.9ms) INSERT INTO "orders" ("description", "created_at", "updated_at") VALUES ($1, $2, $3) RETURNING "id" [["description", "this is a test"], ["created_at", "2019-05-30 23:31:39.409528"], ["updated_at", "2019-05-30 23:31:39.409528"]]
(4.6ms) COMMIT
=> #<Order:0x00007ff91556e4b8 id: 14, description: "this is a test", created_at: Thu, 30 May 2019 23:31:39 UTC +00:00, updated_at: Thu, 30 May 2019 23:31:39 UTC +00:00>
I create an order however when I check for the items it returns an empty array.
=> #<Order:0x00007ff9142da590 id: 14, description: "this is a test", created_at: Thu, 30 May 2019 23:31:39 UTC +00:00, updated_at: Thu, 30 May 2019 23:31:39 UTC +00:00>
[11] pry(main)> Order.last.items
Order Load (0.4ms) SELECT "orders".* FROM "orders" ORDER BY "orders"."id" DESC LIMIT $1 [["LIMIT", 1]]
Item Load (0.3ms) SELECT "items".* FROM "items" WHERE "items"."order_id" = $1 [["order_id", 14]]
=> []
Here is the table for items:
class CreateItems < ActiveRecord::Migration[5.2]
def change
create_table :items do |t|
t.references :order, foreign_key: true
t.integer :quantity
t.string :description
t.timestamps
end
end
end
What is wrong?
The mistake was in the order the parameters were being passed.
{:order=>{:id=>22, :description=>"this is a test", :items_attributes=>[{:order_id=>22, :quantity=>3, :description=>"within order -> item"}]}}
This solved it:
order = Order.create!(params[:order])
<Order:0x00007ff918039ee0 id: 22, description: "this is a test", created_at: Fri, 31 May 2019 01:39:23 UTC +00:00, updated_at: Fri, 31 May 2019 01:39:23 UTC +00:00>
[39] pry(main)> order.items
Item Load (114.8ms) SELECT "items".* FROM "items" WHERE "items"."order_id" = $1 [["order_id", 22]]
=> [#<Item:0x00007ff9180394b8
id: 4,
order_id: 22,
quantity: 3,
description: "within order -> item",
created_at: Fri, 31 May 2019 01:39:23 UTC +00:00,
updated_at: Fri, 31 May 2019 01:39:23 UTC +00:00>]
I am calling this js from a link:
function createNewTopLevelEntry(){
var user_id = $("#user").val();
var header = prompt("Enter the name");
$.ajax( '/users/' + user_id + '/entries', {
data: {
entry: { header: header,
user: user_id } },
type: 'POST',
cache: false,
dataType: 'json',
success: displayTopLevelEntries
});
}
It hits this controller:
def create
#entry = Entry.new(params[:entry])
respond_to do |format|
if #entry.save
format.html { redirect_to #entry, notice: 'Entry was successfully created.' }
format.json { render json: #entry, status: :created, location: #entry }
else
format.html { render action: "new" }
format.json { render json: #entry.errors, status: :unprocessable_entity }
end
end
end
This is the response on the server:
Started POST "/users/1/entries" for 127.0.0.1 at 2013-03-25 21:50:36 -0700
Processing by EntriesController#create as JSON
Parameters: {"entry"=>{"header"=>"Hi", "user"=>"1"}, "user_id"=>"1"}
(0.1ms) begin transaction
SQL (0.5ms) INSERT INTO "entries" ("completed", "created_at", "endtime", "header", "parent", "starttime", "starttimeset", "text", "totaltime", "updated_at", "user") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) [["completed", nil], ["created_at", Tue, 26 Mar 2013 04:50:36 UTC +00:00], ["endtime", nil], ["header", "Hi"], ["parent", nil], ["starttime", nil], ["starttimeset", nil], ["text", nil], ["totaltime", nil], ["updated_at", Tue, 26 Mar 2013 04:50:36 UTC +00:00], ["user", "1"]]
(2.5ms) commit transaction
Completed 500 Internal Server Error in 10ms
NoMethodError - undefined method `entry_url' for #<EntriesController:0x007fb22b9f7fd8>:
(gem) actionpack-3.2.11/lib/action_dispatch/routing/polymorphic_routes.rb:129:in `polymorphic_url'
(gem) actionpack-3.2.11/lib/action_dispatch/routing/url_for.rb:150:in `url_for'
(gem) actionpack-3.2.11/lib/action_controller/metal/rendering.rb:60:in `_process_options'
(gem) actionpack-3.2.11/lib/action_controller/metal/streaming.rb:208:in `_process_options'
(gem) actionpack-3.2.11/lib/action_controller/metal/renderers.rb:34:in `block in _handle_render_options'
What is the entry_url? Why is it looking for it? Do i need to include something in the model. Its just has attr_accessors for the vars.
class Entry < ActiveRecord::Base
attr_accessible :completed, :endtime, :header, :starttime, :starttimeset, :totaltime, :user, :text, :parent
end
Heres is my routes file:
Tasks::Application.routes.draw do
match '/users/:id/projects' => 'users#show_projects_for_user'
authenticated :user do
root :to => 'home#index'
end
root :to => "home#index"
devise_for :users
resources :users do
resources :entries
end
end
Thanks for the help.
The entry_url is what it's asking you to redirect to when you say redirect_to #entry
You don't have an entries resource in the routes file. You do have one nested within user, but then you need to pass as well as the entry.
redirect_to [ #user, #entry ]
just saw your comment - if it's doing this on the JSON path similarly you need to have
location: [#user, #entry]
Basically anywhere you're asking rails to build a url for an entry you need to pass the entry's user in because you have entry nested within user in the routes and not as a standalone resource routing.
Adding an edit to respond to the comment because there's no formatting in comments:
Yes, this it will work to delete the location as it will no longer call the helper to build that location in the json, but I am presuming you want that. So try this to make the location work:
format.json { render json => { :entry => #entry, :status => created, :location => [#user, #entry] }}
from your comment... if that's not working then let's try calling the url helper directly
format.json { render json => { :entry => #entry, :status => created, :location => user_entry_url(#user, #entry) }}
If you are using Rails3, this might case because with rails3, the url has become path
Ex:
#rails2
entry_url
#rails3
entry_path
So try entry_path instead of entry_url
I'm using postgresql in development for the first time and have successfully installed the binary onto my 10.6 machine. I've created a Rails superuser, createdb => 'vitae_development' with this user. It shows up in $pqsl => '/du', but when I key in /dt, I get 'no relations'.
My pg gem is pg-0.12.0
In rails 3.10 console, I enter: User.create!(:name => "Sam", :email => "sam#email.me")
The resulting output is:
INSERT INTO "users" ("created_at", "email", "name", "updated_at") VALUES ($1, $2, $3, $4) RETURNING "id" [["created_at", Wed, 21 Dec 2011 19:40:13 UTC +00:00], ["email", nil], ["name", nil], ["updated_at", Wed, 21 Dec 2011 19:40:13 UTC +00:00]]
That appears to be a bunch of blanks. I've searched the googles but must have missed the right search terms.
pgAdmin3 seems to show the tables in place, as best as I can determine, but with no data that I can find.
This is the relevant snippet from my database.yml:
development:
adapter: postgresql
database: vitae_development
username: rails
password:
pool: 5
timeout: 5000
For completeness, here's the whole user.rb:
class User < ActiveRecord::Base
attr_accessor :name, :email
email_regex = /\A[\w+\-.]+#[a-z\d\-.]+\.[a-z]+\z/i
validates :name, :presence => true,
:length => { :maximum => 50 }
validates :email, :presence => true,
:format => { :with => email_regex },
:uniqueness => { :case_insensitive => false }
end
What am I overlooking? I've done rake db:migrate.
Did you perhaps override the email or email= methods or put attr_accessor :email in your User.rb file?
EDIT:
Take out line 2 where it says attr_accessor :name, :email. attr_accessor in the context of rails is for object variables that won't be saved to the database.
Try eliminating the formatting validation on email...if it works I'd take a deeper look at email_regex
I have two different apps using paperclip. On the app that does not save attachment or call paperclip, i get this log when i upload an app
started POST "/users/1/uploads" for 127.0.0.1 at 2011-04-23 13:38:11 +0100
Processing by UploadsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"t2dRIH4FgOPnLRhpDK0x7iIfjB9Xj5rqkJRPCWZvJ14=", "upload"=> {"document"=>#<ActionDispatch::Http::UploadedFile:0x2beeb08 #original_filename="Essay questions have various requirements.doc", #content_type="application/msword", #headers="Content-Disposition: form-data; name=\"upload[document]\"; filename=\"Essay questions have various requirements.doc\"\r\nContent-Type: application/msword\r\n", #tempfile=#<File:C:/DOCUME~1/Ed/LOCALS~1/Temp/RackMultipart20110423-3980-ycq74p>>}, "commit"=>"Upload", "user_id"=>"1"}
[1m[35mUser Load (0.0ms)[0m SELECT "users".* FROM "users" WHERE "users"."id" = 1 LIMIT 1
[1m[36mUpload Load (0.0ms)[0m [1mSELECT "uploads".* FROM "uploads" WHERE ("uploads".uploadable_id = 1 AND "uploads".uploadable_type = 'User')[0m
Rendered uploads/_uploadify.html.erb (15.6ms)
Rendered uploads/_form.html.erb (31.2ms)
Rendered uploads/new.html.erb within layouts/application (46.9ms)
Completed 200 OK in 500ms (Views: 234.4ms | ActiveRecord: 0.0ms)
On the app where paperclip works fine, i get this log:
Started POST "/uploads" for 127.0.0.1 at Mon Apr 25 11:35:50 +0100 2011
Processing by UploadsController#create as JSON
Parameters: {"_http_accept"=>"application/javascript", "Filename"=>"angels.txt", "folder"=>"/users/", "authenticity_token"=>"NVJj3ODIGuoc97wGvjWkez1YoN+SUDVtNJ+k80XdYXM=", "Upload"=>"Submit Query", "user_id"=>"1", "_uploadify_session"=>"BAh7ByIQX2NzcmZfdG9rZW4iMU5WSmozT0RJR3VvYzk3d0d2aldrZXoxWW9OK1NVRFZ0TkorazgwWGRZWE09Ig9zZXNzaW9uX2lkIiU0ZDEyNzZkNzczNzk1MDdiMmQ4NWZmYTY5MDY4YTU0MQ==--7eb8c0ca249e2566998a0e68322a89d731fdb4ad", "Filedata"=>#<ActionDispatch::Http::UploadedFile:0x4958490 #content_type="application/octet-stream", #original_filename="angels.txt", #tempfile=#<File:C:/DOCUME~1/Ed/LOCALS~1/Temp/RackMultipart20110425-4884-vyvdo8-0>, #headers="Content-Disposition: form-data; name=\"Filedata\"; filename=\"angels.txt\"\r\nContent-Type: application/octet-stream\r\n">}
[paperclip] identify -format %wx%h "C:/DOCUME~1/Ed/LOCALS~1 /Temp/stream20110425-4884-15he32x-0.txt[0]" 2>NUL
[paperclip] convert "C:/DOCUME~1/Ed/LOCALS~1/Temp/stream20110425-4884-15he32x-0.txt[0]" -resize "300x300>" "C:/DOCUME~1/Ed/LOCALS~1/Temp/stream20110425-4884-15he32x-020110425-4884-r65fe6-0" 2>NUL
[paperclip] identify -format %wx%h "C:/DOCUME~1/Ed/LOCALS~1/Temp/stream20110425-4884-15he32x-0.txt[0]" 2>NUL
[paperclip] convert "C:/DOCUME~1/Ed/LOCALS~1/Temp/stream20110425-4884-15he32x-0.txt[0]" -resize "100x100>" "C:/DOCUME~1/Ed/LOCALS~1/Temp/stream20110425-4884-15he32x-020110425-4884-1ttxfol-0" 2>NUL
[1m[36mAREL (15.6ms)[0m [1mINSERT INTO "uploads" ("user_id", "created_at", "photo_file_size", "photo_updated_at", "photo_content_type", "photo_file_name", "updated_at") VALUES (1, '2011-04-25 10:36:10.312500', 867, '2011-04-25 10:35:52.109375', 'text/plain', 'angels.txt', '2011-04-25 10:36:10.312500')[0m
[paperclip] Saving attachments.
[paperclip] saving C:/rails_project1/Uploadify-2/public/system/photos/2/medium/angels.txt
[paperclip] saving C:/rails_project1/Uploadify-2/public/system/photos/2/thumb/angels.txt
[paperclip] saving C:/rails_project1/Uploadify-2/public/system/photos/2/original/angels.txt
Completed 200 OK in 19422ms (Views: 62.5ms | ActiveRecord: 15.6ms)
The only difference between the two is that the one not working is polymorphic model and the controller for the polymorphic model is below:
class UploadsController < ApplicationController
before_filter :find_parent
before_filter :prepare_input_params
#respond_to :html, :json, :js
def index
#uploads = Upload.all
##uploads = #parent.try(:uploads).try(:all)
#upload = Upload.new
#respond_with([#parent, #uploads])
end
def new
#upload = #parent.uploads.new
end
def create
#upload = #parent.uploads.build(params[:upload])
if #upload.save
flash[:notice] = "sucessfully saved upload"
respond_to do |format|
format.html {redirect_to [#parent, :uploads]}
format.json {render :json => { :result => 'success', :upload => polymorphic_url([#parent,:uploads]) } }
end
else
render :action => 'new'
end
end
def edit
#upload = Upload.find(params[:id])
end
def show
"puts #upload.inspect"
#upload = #parent.uploads.find(params[:id])
#total_uploads = #parent.uploads.find(:all, :conditions => { :user_id => #upload.user.id})
end
def update
#upload = Upload.find(params[:id])
if #upload.update_attributes(params[:upload])
flash[:notice] = "Successfully updated document"
redirect_to #upload
else
render :action => 'edit'
end
end
def destroy
#upload = Upload.find(params[:id])
#upload.destroy
redirect_to([#parent, :upload])
end
private
def prepare_input_params
params[:upload][:document] = params[:Filedata] if params[:Filedata]
end
end
Here is the gist file with the form partial and uploadify bit: https://gist.github.com/940960. The form has :html => { :multipart => true }.
Thanks for the help.
EDIT:
It seems the problem is from the model, uploads.rb. When i comment out the section below: everything works, but i need to be able to use validations and specify path as i want to use S3. Anyhelp on how i can uncomment the code without the initial error of paperclip not saving happening again.
class Upload < ActiveRecord::Base
attr_accessible :document
belongs_to :uploadable, :polymorphic => true
has_attached_file :document, :styles => { :small => "150x150>",:thumb => "100x100>" }
=begin
:url => "/uploads/:id/:style/:basename.:extension",
:path => ":rails.root/public/:uploads/:id/:style/:basement.:extension"
validates_attachment_presence :document
validates_attachment_size :document, :less_than => 5.megabytes
validates_attachment_content_type :document, :content_type => ['application/octet-stream','image/jpeg','image/gif', 'image/png', 'image/pdf', 'image/doc',
'video/x-m4v', 'video/quicktime','application/x-shockwave-flash', 'audio/mpeg', 'video/mpeg', 'application/pdf','application/msword']
=end
end
Update:
I think the main problem seem to be that why attaching a new file, paperclip, somehow starts calling SELECT "uploads".*'from "uploads" instead of calling INSERT INTO 'uploads', that is controller#create action shown higher up seems to be calling SELECT, whenever ever i provide :url and :path options to paperclip has_attached_file method. See the log below:
Processing by UploadsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"Azxzi09R7NU7+jxj+lxHFGfs+qw7D6b7yRKegRjRQMc=", "upload"=> {"document"=>#<ActionDispatch::Http::UploadedFile:0x2994ff0 #original_filename="al night verses.txt", #content_type="text/plain", #headers="Content-Disposition: form-data; name=\"upload[document]\"; filename=\"al night verses.txt\"\r\nContent-Type: text/plain\r\n", #tempfile=#<File:C:/DOCUME~1/Ed/LOCALS~1 /Temp/RackMultipart20110505-3444-1rlpnr>>}, "commit"=>"Upload", "user_id"=>"1"}
[1m[35mUser Load (0.0ms)[0m SELECT "users".* FROM "users" WHERE "users"."id" = 1 LIMIT 1
[paperclip] C:\ImageMagick-6.6.3-Q16/identify -format %wx%h "C:/DOCUME~1/Ed/LOCALS~1 /Temp/stream20110505-3444-1cpnf87.txt[0]"
[paperclip] C:\ImageMagick-6.6.3-Q16/convert "C:/DOCUME~1/Ed/LOCALS~1 /Temp/stream20110505-3444-1cpnf87.txt[0]" -resize "150x150>" "C:/DOCUME~1/Ed/LOCALS~1 /Temp/stream20110505-3444-1cpnf8720110505-3444-1vnp5jx"
[paperclip] C:\ImageMagick-6.6.3-Q16/identify -format %wx%h "C:/DOCUME~1/Ed/LOCALS~1 /Temp/stream20110505-3444-1cpnf87.txt[0]"
[paperclip] C:\ImageMagick-6.6.3-Q16/convert "C:/DOCUME~1/Ed/LOCALS~1 /Temp/stream20110505-3444-1cpnf87.txt[0]" -resize "100x100>" "C:/DOCUME~1/Ed/LOCALS~1 /Temp/stream20110505-3444-1cpnf8720110505-3444-1vyk9i"
[1m[36mUpload Load (0.0ms)[0m [1mSELECT "uploads".* FROM "uploads" WHERE ("uploads".uploadable_id = 1 AND "uploads".uploadable_type = 'User')[0m
Rendered uploads/_uploadify.html.erb (15.6ms)
Rendered uploads/_form.html.erb (31.2ms)
Rendered uploads/new.html.erb within layouts/application (62.5ms)
Based on #CharlieMezak's request, here is the views/uploads/_form.html.erb:
<%= debug #parent %>
<%= render :partial => "uploads/uploadify" %>
</br>
<%= form_for [parent, upload], :html => { :multipart => true } do |f| %>
<div class="field">
<%= f.label :document %><br />
<%= f.file_field :document %>
</div>
<div class="actions">
<%= f.submit "Upload"%>
</div>
views/uploads/new.html.erb:
<%= render 'form', :parent => #parent, :upload => #upload %>
views/users/index.html.erb:
<%= render "uploads/form", :parent => user, :upload => user.uploads.new %>
More Update :
Like i mentioned, when i comment out the :styles, : :url and :path options from paperclips's **'has_many_attachment :document', the INSERT statement is called and though it saves the file, instead of displaying the attached file, it ends up displaying several parameters like authenticity tokens etc on the website as shown below:
attributes:
id: 1
email: xyz#yahoo.com
encrypted_password: $2a$10$HiksbkRXDtcXiJyUIRj
password_salt: $2a$10$HiksbkRXD
reset_password_token: !!null
remember_token: !!null
remember_created_at: !!null
sign_in_count: 3
current_sign_in_at: '2011-04-25 18:57:27.078125'
last_sign_in_at: '2011-04-25 09:25:31.406250'
current_sign_in_ip: 127.0.0.1
last_sign_in_ip: 127.0.0.1
created_at: '2011-04-09 17:46:15.546875'
updated_at: '2011-04-25 18:57:27.078125'
changed_attributes: {}
previously_changed: {}
attributes_cache: {}
marked_for_destruction: false
destroyed: false
readonly: false
new_record: false
Did you remember to add :multipart => true to the form tag in your view?
Try adding :document_file_name to the attr_accessible call.
One thing I noticed is there is a typo on line 17 of uploadify in your gist. You have dat.upload, probably should be data.upload?
Also, have you tried uncommenting the validations one at a time? Let me know what happens. I've had my fair share of battles versus Paperclip.
I'm doing exactly the same kind of thing as you are, but using the aws-s3 gem to help me upload to S3 via paperclip. This is what's in my model:
has_attached_file :image,
:storage => :s3,
:s3_credentials => "#{Rails.root.to_s}/config/s3.yml",
:bucket => "your_s3_bucket_name",
:path => ":attachment/:id/:style/:filename"
And I have this in my gemfile:
gem "paperclip", "~> 2.3"
gem "aws-s3"
And in my groups table:
t.string "image_file_name"
t.string "image_content_type"
t.integer "image_file_size"
t.datetime "image_updated_at"
I have implemented a form with image upload using paperclip on rails 3.0.1 on linux
(same problem below on rails 3.0.0 on windows)
Whatever I enter in my form, I get the Type Error "can't convert hash into integer".
The strange thing is that it worked 1 time (form submit + file upload). I probably changed something somewhere in the code and it never worked again. (I cannot figure where I wen wrong)
View:
<% form_for(#account,:url=>{ :action=>'create' },:html => { :multipart => true }) do |f| %>
<%= render :partial => 'form', :locals => { :f => f } %>
<%= f.submit %>
<% end %>
_form:
<%= f.error_messages %>
<%= f.text_field :company_name %><br />
<%= f.text_field :code %><br />
<%= f.text_field :website %><br />
<%= f.file_field :logo %><br />
<%= f.collection_select('industry_id', #industries, :id, :label, :include_blank=>true) %>
controller:
def new
#industries = Industry.find(:all, :order => 'label')
#account = Account.new
end
def create
#account = Account.new(params[:account])
#account.begin_date = DateTime.now
#account.active = 1
if #account.save #LINE 247:
flash[:notice] = 'Account was successfully created.'
redirect_to :action => 'show', :id => #account.id
else
render :action => 'new'
end
end
model:
has_attached_file :logo,
:styles => {
:thumb=> "100x100#",
:small => "150x150>",
:medium => "300x300>",
:large => "400x400>" },
:url => "/logos/:id/:style/:basename.:extension",
:path => ":rails_root/public/logos/:id/:style/:basename.:extension"
LOG:
Started POST "/accounts/create" for 127.0.0.1 at 2010-11-13 10:08:27 +0800
[1m[36mSQL (31.2ms)[0m [1mdescribe `groups_users`[0m
Processing by AccountsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"ihg8Il2eHnMj/q9KmZPzOSB8W7NDs3hbpkEJ+WSHd10=", "account"=>{"company_name"=>"aa and co", "code"=>"aaco", "website"=>"aa.com", "logo"=>#<File:/usr/tmp/RackMultipart20101113-3624-oowopi>, "industry_id"=>"1"}, "commit"=>"Create Account"}
[1m[35mUser Load (0.0ms)[0m SELECT `users`.* FROM `users` WHERE (`users`.`id` = 1) LIMIT 1
[1m[36mUserType Load (0.0ms)[0m [1mSELECT `user_types`.* FROM `user_types` WHERE (`user_types`.`id` = 1) LIMIT 1[0m
[paperclip] identify -format %wx%h "/usr/tmp/stream20101113-3624-s1ybvo.jpg[0]" 2>NUL
[paperclip] convert "/usr/tmp/stream20101113-3624-s1ybvo.jpg[0]" -resize "100x" -crop "100x100+0+2" +repage "/usr/tmp/stream20101113-3624-s1ybvo20101113-3624-7z7f43" 2>NUL
[paperclip] identify -format %wx%h "/usr/tmp/stream20101113-3624-s1ybvo.jpg[0]" 2>NUL
[paperclip] convert "/usr/tmp/stream20101113-3624-s1ybvo.jpg[0]" -resize "150x150>" "/usr/tmp/stream20101113-3624-s1ybvo20101113-3624-124zkow" 2>NUL
[paperclip] identify -format %wx%h "/usr/tmp/stream20101113-3624-s1ybvo.jpg[0]" 2>NUL
[paperclip] convert "/usr/tmp/stream20101113-3624-s1ybvo.jpg[0]" -resize "300x300>" "/usr/tmp/stream20101113-3624-s1ybvo20101113-3624-1jd454b" 2>NUL
[paperclip] identify -format %wx%h "/usr/tmp/stream20101113-3624-s1ybvo.jpg[0]" 2>NUL
[paperclip] convert "/usr/tmp/stream20101113-3624-s1ybvo.jpg[0]" -resize "400x400>" "/usr/tmp/stream20101113-3624-s1ybvo20101113-3624-w8mrk8" 2>NUL
[1m[35mSQL (0.0ms)[0m BEGIN
[1m[36mSQL (0.0ms)[0m [1mROLLBACK[0m Completed in 1547ms
TypeError (can't convert Hash into Integer):
app/controllers/accounts_controller.rb:247:in `create'
I'm guessing the error comes from the form, but I can't figure where.
Any help would greatly appreciated.
The strangest thing is that this form worked twice:
Yesterday morning, just after starting the computer, I launched the app, submitted the form and it worked. Later I haven't managed to make it work again at all (and I haven't changed anything)
This morning, I started the computer and could submit the form (haven't tried with the image at that time). Trying again and it failed. Restarting the computer was useless.
What I am doing now is removing all but 1 field from the form, and any code from the controller except: #account.save, but i still get the same error, ignoring the validations in my model...
I also tried with a html form directly hardcoded in the view (not using form_for or form_tag) and i was getting the same result. So it's probably safe to assume the problem doesn't comme from the controller or the view... (and it's not a paperclip issue either)
Problem fixed! Two days of fighting with a code that wasn't at fault... :(
The error came from a validation in my model!
validates_length_of :code, :is=>9, :message=>"has %d chars"
The only times when it worked as was probably entering 9 characters and the validation didn't have to display the %d message...