I'm using tinymce-rails-image-upload to upload images with paperclip (following this demo-app). When I try to upload an image I'm getting an 'umpermitted parameters' reminder and the image doesn't upload. The upload modal shows 'Got a bad response from server':
Processing by TinymceAssetsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"auth token", "hint"=>"", "file"=>#<ActionDispatch::Http::UploadedFile:0x000001025a2780 #tempfile=# <File:/var/folders/t4/86vsrmds42j84r36kwpng7k00000gn/T/RackMultipart20150207- 12522-9rj6xq>, #original_filename="applecash.jpg", #content_type="image/jpeg", #headers="Content-Disposition: form-data; name=\"file\"; filename=\"applecash.jpg\"\r\nContent-Type: image/jpeg\r\n">, "alt"=>""}
Command :: identify -format '%wx%h,%[exif:orientation]' '/var/folders/t4/86vsrmds42j84r36kwpng7k00000gn/T/RackMultipart20150207-12522-9rj6xq[0]' 2>/dev/null
Unpermitted parameters: utf8, authenticity_token
(0.1ms) begin transaction
Question Load (0.5ms) SELECT "questions".* FROM "questions" WHERE (questions.position IS NOT NULL) AND (1 = 1) ORDER BY questions.position DESC LIMIT 1
Binary data inserted for `string` type on column `file_content_type`
SQL (0.8ms) INSERT INTO "questions" ("created_at", "file_content_type", "file_file_name", "file_file_size", "file_updated_at", "position", "updated_at") VALUES (?, ?, ?, ?, ?, ?, ?) [["created_at", Sun, 08 Feb 2015 18:35:07 UTC +00:00], ["file_content_type", "image/jpeg"], ["file_file_name", "timcook.jpg"], ["file_file_size", 120040], ["file_updated_at", Sun, 08 Feb 2015 18:35:07 UTC +00:00], ["position", 9], ["updated_at", Sun, 08 Feb 2015 18:35:07 UTC +00:00]]
(7.3ms) commit transaction
Completed 200 OK in 68ms (Views: 0.6ms | ActiveRecord: 8.7ms)
Here's the controller:
class TinymceAssetsController < ApplicationController
respond_to :json
def create
geometry = Paperclip::Geometry.from_file params[:file]
question = Question.create params.permit(:file, :alt, :hint)
render json: {
question: {
url: question.file.url,
height: geometry.height.to_i,
width: geometry.width.to_i
}
}, layout: false, content_type: "text/html"
end
end
and the question model:
class Question < ActiveRecord::Base
has_attached_file :file
end
and the view:
<%= simple_form_for [#comment, Question.new] do |f| %>
<%= f.text_area :body, :class => "tinymce", :rows => 10, :cols => 60 %>
<% end %>
<%= tinymce plugins: ["uploadimage"] %>
It's ok to not permit some of the parameters, so Unpermitted parameters: utf8, authenticity_token is a reminder, not an exception. I suggest you log what are question model instance errors:
question = Question.create params.permit(:file, :alt, :hint)
logger.debug question.errors.full_messages
May be wrong, but, you have the following:
question = Question.create params.permit(:file, :alt, :hint)
I think you'd just make that read like this and it would work:
question = Question.create params.permit(:file, :alt, :hint, :utf8, :authenticity_token)
The error is clear. You have not permitted those parameters. But they exist. You expressly permit the other three there so I presume you have to permit those two additional.
That's my guess and I'm sticking to it :).
Related
I'm trying to upload images using paperclip and tinymce-rails-image-upload following this demo. I'm uploading images in a question model (that belongs to comments). When I upload, I get a 'got a bad response from the server' message and the image isn't shown in the editor, however it does create a new question.
Here is my the log after upload:
Processing by TinymceAssetsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"auth token", "hint"=>"", "file"=>#<ActionDispatch::Http::UploadedFile:0x000001025a2780 #tempfile=# <File:/var/folders/t4/86vsrmds42j84r36kwpng7k00000gn/T/RackMultipart20150207- 12522-9rj6xq>, #original_filename="applecash.jpg", #content_type="image/jpeg", #headers="Content-Disposition: form-data; name=\"file\"; filename=\"applecash.jpg\"\r\nContent-Type: image/jpeg\r\n">, "alt"=>""}
Command :: identify -format '%wx%h,%[exif:orientation]' '/var/folders/t4/86vsrmds42j84r36kwpng7k00000gn/T/RackMultipart20150207-12522-9rj6xq[0]' 2>/dev/null
Unpermitted parameters: utf8, authenticity_token
(0.1ms) begin transaction
Question Load (0.5ms) SELECT "questions".* FROM "questions" WHERE (questions.position IS NOT NULL) AND (1 = 1) ORDER BY questions.position DESC LIMIT 1
Binary data inserted for `string` type on column `file_content_type`
SQL (0.8ms) INSERT INTO "questions" ("created_at", "file_content_type", "file_file_name", "file_file_size", "file_updated_at", "position", "updated_at") VALUES (?, ?, ?, ?, ?, ?, ?) [["created_at", Sun, 08 Feb 2015 18:35:07 UTC +00:00], ["file_content_type", "image/jpeg"], ["file_file_name", "timcook.jpg"], ["file_file_size", 120040], ["file_updated_at", Sun, 08 Feb 2015 18:35:07 UTC +00:00], ["position", 9], ["updated_at", Sun, 08 Feb 2015 18:35:07 UTC +00:00]]
(7.3ms) commit transaction
Completed 200 OK in 68ms (Views: 0.6ms | ActiveRecord: 8.7ms)
Here is the tinymce controller:
class TinymceAssetsController < ApplicationController
respond_to :json
def create
geometry = Paperclip::Geometry.from_file params[:file]
question = Question.create params.permit(:file, :alt, :hint)
render json: {
question: {
url: question.file.url,
height: geometry.height.to_i,
width: geometry.width.to_i
}
}, layout: false, content_type: "text/html"
end
end
The questions controller create action looks like this (do I add #comment and the additional parameters to the tinymce controller?):
def create
#comment = Comment.find(params[:comment_id])
#question = #comment.questions.new(question_params)
end
...
def question_params
params.require(:question).permit(:body, :comment_id, :user_id, :file, :position)
end
The question model:
class Question < ActiveRecord::Base
has_attached_file :file
end
and the editor view:
<%= simple_form_for [#comment, Question.new] do |f| %>
<%= f.text_area :body, :class => "tinymce", :rows => 10, :cols => 60 %>
<% end %>
<%= tinymce plugins: ["uploadimage"] %>
I'm confused as to why its creating a new question for every uploaded image and what's still causing the 'bad response' error.
it seems tinymce-rails-imageupload expects "image" in response to uploaded file
render json: {
image: {
url: question.file.url,
height: geometry.height.to_i,
width: geometry.width.to_i
}
}, layout: false, content_type: "text/html"
I have a multiselect (using bootstrap-multiselect) in my #minisets new form that aims to associate #scales with the #miniset via the #sizes table.
The associations work fine. What I'm stuck on is how to loop through the multiple :scale_id submissions from the multiselect and create lines in the #sizes table for them all.
Following this answer I have been trying to use split and then loop the create but I think the fact that that answer pertains to a HABTM relationship and mine is has_many_through means I need a different solution?
In my minisets controller I have
def new
#miniset = Miniset.new
#miniset.sizes.build
end
def create
#miniset = Miniset.new(miniset_params)
if #miniset.save
params[:scale_id].split(',').each do |id|
#miniset.sizes.create(params[:sizes_attributes])
end
redirect_to #miniset
else
render 'new'
end
end
private
def miniset_params
params.require(:miniset).permit(:name, :release_date, :material, :pcode, :notes, :quantity, :random, productions_attributes: [:id, :manufacturer_id, :miniset_id], sizes_attributes: [:id, :scale_id, :miniset_id], sculptings_attributes: [:id, :sculptor_id, :miniset_id])
end
end
In my view I have
<%= f.fields_for :sizes do |size_fields| %>
<%= size_fields.label :scale_id, simple_pluralize(#miniset.scales.count, 'Scale') %>
<%= size_fields.select :scale_id,
options_from_collection_for_select(Scale.all, :id, :name, #miniset.scales.map(&:id)),
{},
{class: 'multiselect', multiple: true} %>
<% end %>
<script type="text/javascript">
$(document).ready(function() {
$('.multiselect').multiselect();
});
</script>
I'm currently getting error undefined methodsplit' for nil:NilClass` when I submit.
I think that may be because the log shows an empty scale_id passed before the two filled ones and split won't accept nil? Here is the log when submitting TWO scales.
Started POST "/minisets" for 127.0.0.1 at 2014-01-30 10:49:59 +0000
Processing by MinisetsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"R0RxDMwB5/ytSb5qgjIlVR5as0/DTkstgFMDXcefDnc=", "miniset"=>{"name"=>"Test for size", "quantity"=>"10", "random"=>"0", "material"=>"Hard Plastic", "sizes_attributes"=>{"0"=>{"scale_id"=>["", "1", "5"]}}, "pcode"=>"", "release_date(1i)"=>"", "release_date(2i)"=>"", "release_date(3i)"=>"", "notes"=>""}, "Set Scale"=>{"#<ActiveRecord::Associations::CollectionProxy::ActiveRecord_Associations_CollectionProxy_Size:0x007fcf643c29f0>"=>""}, "commit"=>"Add set"}
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."remember_token" = 'd59f28d384d62b71719dd845b4e5353cdd993016' LIMIT 1
Unpermitted parameters: scale_id
SQL (0.9ms) INSERT INTO "minisets" ("created_at", "material", "name", "notes", "pcode", "quantity", "updated_at") VALUES (?, ?, ?, ?, ?, ?, ?) [["created_at", Thu, 30 Jan 2014 10:49:59 UTC +00:00], ["material", "Hard Plastic"], ["name", "Test For Size"], ["notes", ""], ["pcode", ""], ["quantity", 10], ["updated_at", Thu, 30 Jan 2014 10:49:59 UTC +00:00]]
SQL (0.6ms) INSERT INTO "sizes" ("created_at", "miniset_id", "updated_at") VALUES (?, ?, ?) [["created_at", Thu, 30 Jan 2014 10:49:59 UTC +00:00], ["miniset_id", 41], ["updated_at", Thu, 30 Jan 2014 10:49:59 UTC +00:00]]
(4.2ms) commit transaction
Completed 500 Internal Server Error in 153ms
NoMethodError (undefined method `split' for nil:NilClass):
app/controllers/minisets_controller.rb:19:in `create'
I'm sure what I have after the split is incorrect but I can't play with it until the split works. I can get rid of the error by adding to_s before the split but I get no better results.
Been making very slow progress on this multiselect for days now so any help very much appreciated.
Thanks to this fantastic youtube video I solved my problem.
My form:
<%= f.fields_for(#size) do |sf| %>
<%= sf.label simple_pluralize(#miniset.scales.count, 'Scale') %>
<%= collection_select( :scales, :id, #all_scales, :id, :name,
{},
{class: 'multiselect', multiple: true}) %>
<% end %>
In my minisets_controller I have the following new and create actions:
def new
#miniset = Miniset.new
#all_scales = Scale.all
#size = #miniset.sizes.build
end
def create
#miniset = Miniset.new(miniset_params)
params[:scales][:id].each do |scale|
if !scale.empty?
#miniset.sizes.build(:scale_id => scale)
end
end
if #miniset.save
redirect_to #miniset
else
render 'new'
end
end
It works perfectly. If anyone else is having the same problem, trying to get multiselects to work in rails with has_many_through, I recommend watching that video. So pleased.
I'm using Paperclip and Remotipart to handle some AJAX file uploads (uploads and display images with AJAX).
I'm using Rails 3.2.11
The problem is, while the record is being created, the attachment fields are all nil and no image actually gets uploaded. Here is the small form:
<%= form_tag("/portfolios/upload_port_img", method: "post", :html => { :multipart => true }, remote: true, :class=>'fileup') do |t| %>
<% file_field_tag(:attachment) %>
<% end %>
When I submit the form, I get this response:
Processing by PortfoliosController#upload_port_img as JS
Parameters: {"utf8"=>"✓", "authenticity_token"=>"+/pPeTYu9filNt5M2+BNYIc9+8kzLyo4pvCB6oMC0U0=", "remotipart_submitted"=>"true", "X-Requested-With"=>"IFrame", "X-Http-Accept"=>"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript, */*; q=0.01", "attachment"=>#<ActionDispatch::Http::UploadedFile:0x00000003417488 #original_filename="6jPQg1l.jpg", #content_type="image/jpeg", #headers="Content-Disposition: form-data; name=\"attachment\"; filename=\"6jPQg1l.jpg\"\r\nContent-Type: image/jpeg\r\n", #tempfile=#<File:/tmp/RackMultipart20131123-10843-h6wdmc>>}
(0.1ms) begin transaction
SQL (4.3ms) INSERT INTO "portfolio_files" ("attachment_content_type", "attachment_file_name", "attachment_file_size", "attachment_updated_at", "created_at", "description", "portfolio_id", "position", "updated_at") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) [["attachment_content_type", nil], ["attachment_file_name", nil], ["attachment_file_size", nil], ["attachment_updated_at", nil], ["created_at", Sat, 23 Nov 2013 23:41:27 UTC +00:00], ["description", nil], ["portfolio_id", nil], ["position", nil], ["updated_at", Sat, 23 Nov 2013 23:41:27 UTC +00:00]]
[paperclip] Saving attachments.
(9.4ms) commit transaction
Rendered portfolios/upload_port_img.js.erb (31.4ms)
Completed 200 OK in 131ms (Views: 69.6ms | ActiveRecord: 14.1ms)
Yet still, no image is uploaded. Any idea why this may be?
I just realized when I use after_commit filter, it seems to be executing the function twice (reasons unknown to me)
Controller:
def new
#upload_files = UploadFiles.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: #upload_files }
end
end
# GET /uploads/1/edit
def edit
#uploadFiles = Upload.find(params[:id])
end
# POST /uploads
# POST /uploads.json
def create
#upload_files = UploadFiles.create(params[:upload_files])
respond_to do |format|
if #upload_files.save
redirect_to #upload_files
else
format.html { render action: "new" }
format.json { render json: #upload_files.errors, status: :unprocessable_entity }
end
end
end
template:
<%= csrf_meta_tags %>
<%= form_for :upload_files, :url => upload_files_path, :html => { :multipart => true } do |f| %>
<h4>Upload Inventory</h4>
<div><%= f.file_field :inventory %></div>
<h4>Upload Material List</h4>
<div><%= f.file_field :material_list %></div>
<div align="center">
<%= f.submit "Upload" %>
</div>
<% end %>
class UploadFiles < ActiveRecord::Base
after_save :process_files
def process_files
#init_process=Time.now
out_file = File.new("times.txt", "w")
out_file.puts("Init Time")
out_file.puts(Time.now)
logger.info "Processing the request..."
logger.info Time.now
logger.info "Processing Files..."
logger.info Time.now
.
.
.
end
end
Log:
Started POST "/upload_files" for 127.0.0.1 at 2013-10-17 10:20:06 -0430
Processing by UploadFilesController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"NpCyDUNq8uPwJMj2DofP4rHEZWYkfsIu68Wg+XqebNk=", "upload_files"=>{"inventory"=>#<ActionDispatch::Http::UploadedFile:0x4df7648 #original_filename="INV Onhand -753233-2013090621595800.xlsx", #content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", #headers="Content-Disposition: form-data; name=\"upload_files[inventory]\"; filename=\"INV Onhand -753233-2013090621595800.xlsx\"\r\nContent-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\r\n", #tempfile=#<File:C:/Users/V80042~1/AppData/Local/Temp/RackMultipart20131017-7356-1i1m655>>, "material_list"=>#<ActionDispatch::Http::UploadedFile:0x4df7408 #original_filename="Formato SCL Movistar1.xlsx", #content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", #headers="Content-Disposition: form-data; name=\"upload_files[material_list]\"; filename=\"Formato SCL Movistar1.xlsx\"\r\nContent-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\r\n", #tempfile=#<File:C:/Users/V80042~1/AppData/Local/Temp/RackMultipart20131017-7356-fqdioq>>}, "commit"=>"Upload"}
[1m[35mUser Load (0.0ms)[0m SELECT "users".* FROM "users" WHERE "users"."id" = 5 LIMIT 1
[1m[36m (0.0ms)[0m [1mbegin transaction[0m
Binary data inserted for `string` type on column `inventory_content_type`
Binary data inserted for `string` type on column `material_list_content_type`
[1m[35mSQL (2.0ms)[0m INSERT INTO "upload_files" ("created_at", "inventory_content_type", "inventory_file_name", "inventory_file_size", "inventory_updated_at", "material_list_content_type", "material_list_file_name", "material_list_file_size", "material_list_updated_at", "updated_at") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) [["created_at", Thu, 17 Oct 2013 14:50:06 UTC +00:00], ["inventory_content_type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"], ["inventory_file_name", "INV_Onhand_-753233-2013090621595800.xlsx"], ["inventory_file_size", 6776337], ["inventory_updated_at", Thu, 17 Oct 2013 14:50:06 UTC +00:00], ["material_list_content_type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"], ["material_list_file_name", "Formato_SCL_Movistar1.xlsx"], ["material_list_file_size", 42608], ["material_list_updated_at", Thu, 17 Oct 2013 14:50:06 UTC +00:00], ["updated_at", Thu, 17 Oct 2013 14:50:06 UTC +00:00]]
[1m[36m (4.0ms)[0m [1mcommit transaction[0m
Processing the request...
2013-10-17 10:20:07 -0430
Processing Files...
2013-10-17 10:20:07 -0430
Inventory Opened...
2013-10-17 10:21:47 -0430
Material List Opened...
2013-10-17 10:21:48 -0430
Default Sheets were set...
Output file created...
2013-10-17 10:21:48 -0430
Code and Name read...
2013-10-17 10:21:48 -0430
Beginning Inventory reading...
2013-10-17 10:21:48 -0430
Inventory completely read...
2013-10-17 10:57:54 -0430
Total Time reading and Parsing Inventory...
2013-10-17 10:57:54 -0430
Output file created...
2013-10-17 10:58:00 -0430
Process Finished...
2013-10-17 10:58:00 -0430
[1m[35m (1095.0ms)[0m begin transaction
[1m[36m (19.0ms)[0m [1mcommit transaction[0m
Processing the request...
2013-10-17 10:58:03 -0430
Processing Files...
2013-10-17 10:58:03 -0430
failed to allocate memory
Redirected to http://localhost:3000/upload_files/157
Completed 406 Not Acceptable in 2293951ms (ActiveRecord: 1124.0ms)
The file is obviously too large and it throws failed to allocate memory but if it didn't i'm pretty sure it would execute it again...
Why does it execute it again?
I tried using after_create and after_save but it throws an exception saying the .xlsx files aren't present.
Assuming I understood what you meant correctly, you're doing multiple saves in your controller's create action, as both UploadFiles.create and #upload_files.save trigger a database operation.
Perhaps you meant UploadFiles.new?
I'm getting an error on the show action when new guidelines are being added to my app. This is since I changed the show action to allow for custom routes...The new guideline is added to the database correctly...
My show action in guidelines_controller.rb is
def show
#guideline = Guideline.where(title: params[:title]).first
respond_to do |format|
format.html # show.html.erb
format.json { render json: #guideline }
end
end
model guidelines.rb is
attr_accessible :content, :hospital, :title, :user_id, :guideline_id, :specialty
show view is
<p>Title: <%= link_to #guideline.title, seeguideline_path(#guideline.title) %> </p
Error message is
console says...
Started POST "/guidelines" for 127.0.0.1 at 2013-02-22 17:07:29 +1100
Processing by GuidelinesController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"bQKIkSb4Wzr46FERMbU82Q1qMzd3GrGNq6Nqmr0KNhY=", "guideline"=>{"title"=>"Stackoverflo", "specialty"=>"Dermatology", "hospital"=>"Stack Hospital", "content"=>"www.stackoverflow.com"}, "commit"=>"Create Guideline"}
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = 11 LIMIT 1
(0.1ms) begin transaction
Guideline Exists (0.4ms) SELECT 1 AS one FROM "guidelines" WHERE (LOWER("guidelines"."hospital") = LOWER('Stack Hospital') AND "guidelines"."title" = 'Stackoverflo') LIMIT 1
SQL (65.0ms) INSERT INTO "guidelines" ("content", "created_at", "hospital", "specialty", "subtitle", "title", "updated_at", "user_id") VALUES (?, ?, ?, ?, ?, ?, ?, ?) [["content", "www.stackoverflow.com"], ["created_at", Fri, 22 Feb 2013 06:07:29 UTC +00:00], ["hospital", "Stack Hospital"], ["specialty", "Dermatology"], ["subtitle", nil], ["title", "Stackoverflo"], ["updated_at", Fri, 22 Feb 2013 06:07:29 UTC +00:00], ["user_id", 11]]
SOLR Request (152.5ms) [ path=#<RSolr::Client:0x007f9c79f2fc48> parameters={data: <?xml version="1.0" encoding="UTF-8"?><add><doc><field name="id">Guideline 35</field><field name="type">Guideline</field><field name="type">ActiveRecord::Base</field><field name="class_name">Guideline</field><field name="title_text">Stackoverflo</field></doc></add>, headers: {"Content-Type"=>"text/xml"}, method: post, params: {:wt=>:ruby}, query: wt=ruby, path: update, uri: http://localhost:8982/solr/update?wt=ruby, open_timeout: , read_timeout: } ]
(3.7ms) commit transaction
Redirected to http://localhost:3000/guidelines/35
SOLR Request (100.3ms) [ path=#<RSolr::Client:0x007f9c79f2fc48> parameters={data: <?xml version="1.0" encoding="UTF-8"?><commit/>, headers: {"Content-Type"=>"text/xml"}, method: post, params: {:wt=>:ruby}, query: wt=ruby, path: update, uri: http://localhost:8982/solr/update?wt=ruby, open_timeout: , read_timeout: } ]
Completed 302 Found in 485ms (ActiveRecord: 69.8ms)
Started GET "/guidelines/35" for 127.0.0.1 at 2013-02-22 17:07:30 +1100
Processing by GuidelinesController#show as HTML
Parameters: {"id"=>"35"}
Guideline Load (0.2ms) SELECT "guidelines".* FROM "guidelines" WHERE "guidelines"."id" = ? LIMIT 1 [["id", "35"]]
Guideline Load (0.2ms) SELECT "guidelines".* FROM "guidelines" WHERE "guidelines"."title" IS NULL LIMIT 1
Rendered guidelines/show.html.erb within layouts/application (18.3ms)
Completed 500 Internal Server Error in 83ms
ActionView::Template::Error (undefined method `title' for nil:NilClass):
6:
7: <div class="guideline span10">
8:
9: <p>Title: <%= link_to #guideline.title, seeguideline_path(#guideline.title) %> </p>
10: <strong> <a href="<%= #guideline.content %>", target = '_blank'>Link to guideline</a> </strong>
11: <p>Hospital Name: <%= #guideline.hospital %></p>
12:
app/views/guidelines/show.html.erb:9:in `_app_views_guidelines_show_html_erb__4234346501713687788_70155056040280'
app/controllers/guidelines_controller.rb:132:in `show'
route is
get '/:title', to: 'guidelines#show', as: :seeguideline
Are you sure your route is passing the :title param? What does your console log show for the SQL request for the query? I have a feeling your route isn't passing what you think it's passing...
Also, you're going to want to handle the case that the query comes back empty anyway. Having the app blow up probably isn't what you want.