I am using Rails 4. I want to upload multiple files of type doc, doc.x, pdf etc, but not any image file. I implemented 'jquery-fileupload-rails' gem. But while uploading it shows "Internal Server Error".
Can you help me with this issue? Or is there any other way to upload multiple files of above mentioned file type?
you can use the gem Papaerclip available in rails for uploading images and files of any type.
Have a look in this article I wrote
http://www.abhijat.name/2013/08/carrierwave-s3-fog-jquery-file-upload-vs-cors-html5-canvas.html?m=1
As mentioned by the other responses, you're going to need to use an attachment-handling gem, such as Paperclip or Carrierwave
The problem you have is that although the JQuery upload gem is working to send files to your server, Rails doesn't know how to handle the files you send, hence why you're seeing the 500 error
Paperclip
We love Paperclip - it's perfect for uploading any attachment to your server
Here's how to use it:
#GemFile
gem "paperclip", "~> 3.5.2"
#app/models/attachment.rb
Class Attachment < ActiveRecord::Base
has_attached_file :attachment
end
#db/migrate
def change
create_table :attachments do |t|
t.attachment :attachment
t.timestamps
end
end
#app/controllers/attachments_controller.rb
def new
#attachment = Attachment.new
end
def create
#attachment = Attachment.new(attachment_params)
#attachment.save
end
private
def attachment_params
params.require(:attachment).permit(:attachment)
end
#app/views/attachments/new.html.erb
<%= form_for #attachment, {multipart: true} do |f| %>
<%= f.file_field :attachment %>
<%= f.submit %>
<% end %>
Hope this helps?
Related
I am searching for the internet about this topic, but I don't get how AJAX works with rails, I already check the documentation and I just simply don't understand it.
What I know is that AJAX is asynchronous and it just only takes to put this code in the view for make the request: "remote:true", the big deal that I don't get it is about this code:
respond_to :js
Apparently, it tells the controller that it would respond to Javascript and you have to make a file for whatever you wanna do with JS, my structure of my project is this one:
View
New.html.erb:
<p>Imagen de portada</p>
<%= simple_form_for #entries, remote: true do |f| %>
<% f.file_field 'input-image' %>
<% end %>
<div id="image-entry"></div>
View route:
views
|
-->admins
|
-->entries
|-->new.html.erb
|-->new.js.erb
Controller
entries_controller.rb
module Admins
class EntriesController < ApplicationController
before_action :authenticate_admin!
def index
render 'index'
end
def new
#entries=''
render 'new'
respond_to :js
end
end
end
Controller route:
controllers
|
-->admins
|
-->entries_controller.erb
JS
new.js.erb
console.log('funciona');
$('#input-image').click(function(){
$('body').css('background-color', 'red');
});
JS route:
views
|
-->admins
|
-->entries
|-->new.html.erb
|-->new.js.erb
Error
My error in this code is the following:
ActionController::UnknownFormat
So, I have questions about this error and what is the correct name of the file in JS for get the respond_to work correctly.
Answer by Irfan Fadilah on Facebook:
Your request is not processed by "new" method in EntriesController. The default form method is POST, so Rails will looking for "create" method in you EntriesController.
You can read RESTful routing in Rails Guide for more details.
In order to make your AJAX request to works. Add "create" method in EntriesController and create.js.erb (just write alert("Hello"); or something to test it) in views/entries.
I have the following link_to helper:
# app/views/users/show.html.erb
<div id="social">
<%= link_to "Friends", index_friends_path, id: "index_friends", remote: true %>
</div>
Since the value of :remote is set to true, my expectation was that the server would naturally try to return JavaScript with the AJAX response.
However, each time the link is clicked the AJAX response contains HTML from a file called users/friends.html.erb rather than JavaScript that dynamically renders the HTML from users/_friends.html.erb which would be the required behaviour.
My code for handling the request is as follows:
--Route:
# config/routes.rb
get '/index_friends' => 'users#friends'
--Action:
# app/controllers/users_controller.rb
def friends
...
respond_to do |format|
format.js
format.html
end
end
--js.erb template:
# app/views/friends.js.erb
$("#social").html("<%= j(render("friends")) %>");
The corresponding Rails log entry looks like this:
# log/development.log
Started GET "/index_friends" for 127.0.0.1 at 2015-09-13 12:20:41 +0100
Processing by UsersController#friends as JS
Try
"data-type" => "js"
after
remote: true
The friends.js.erb file was in the wrong directory (app/views/ as opposed to app/views/users).
To remedy this I ran the following in the terminal:
mv app/views/friends.js.erb app/views/users/friends.js.erb
Rails can now find this template since, by convention, the format instructions from the users controller point to files in app/views/users.
I have just created a simple Rails 4.2 application to upload file to S3. I'm trying to follow this article https://devcenter.heroku.com/articles/direct-to-s3-image-uploads-in-rails#submitting-and-rendering-the-images and it looks like in javascript <%= #variable %> gets parsed as string.
I tried this.
This is what I have in /users/new
# GET /users/new
def new
#s3_direct_post = S3_BUCKET.presigned_post(key: "uploads/#{SecureRandom.uuid}/${filename}", success_action_status: 201, acl: :public_read)
#user = User.new
end
And this is what I tried in application.js
window.vaz = <%= #s3_direct_post.url %>;
but when I do console.log(window.vaz); I get "<%= #s3_direct_post.url %>" instead of the real value.
I tried gon as well but gon has a lot of issues with Rails 4.2
I verified that #s3_direct_post.url returns something in the console.
Add .erb extension to application.js file (application.js.erb). <%= => is erb syntax and you need to process it as erb file first so that <%= #s3_direct_post.url %> is evaluated as ruby code.
http://guides.rubyonrails.org/asset_pipeline.html#preprocessing
I was trying to solve this problem for a while with no result.
I've wanted to pass variables and load a render into a div using CoffeeScript in rails 4.
(I'm using SpreeCommerce platform).
view:
<%= link_to taxonomy.name,root_path+'t/'+tid, {class: "uno", remote: true} %>
controller:
respond_to do |format|
format.html
format.js # menu.js.coffee.erb
end
menu.js.erb.coffee:
$('div#productos').html("<%= escape_javascript(render :partial => /shared/products) %>")
I'd like to load the page '_products.erb.html' and the partial processes the variables that I give it. As soon as I know, view and controller are ok, the problem is in menu.js.erb.coffee
Any help will be apreciated!
ADDITIONAL:
I've modified the extension to .js.coffee.erb. When I try to run the app, it shows me:
"undefined method `render' for #<#:0xa70317c>"
I tryied using <%= raw escape_javascript( render :partial =>... almost always "render" method give me problems.
NEW INFO:
I added gem 'coffee-script' to the Gemfile (then 'bundle install').
Now, when I click the link_to, it shows me into the HTML <%= escape_javascript(render :partial => /shared/products) %> as a text instead of loading the "partial"... any suggestion please?
I wrote a post about this after struggling through the same problem.
You need to:
Name it menu.js.coffee. Suffixing .erb causes it not to be evaluated as CoffeeScript.
Use raw to escape it.
I used these two on my website. Here's how it looks:
<%= raw render 'path/to/menu.js.coffee' %>
It still processes ERB within your CoffeeScript.
I would recommend changing it from menu.js.erb.coffee to menu.js.coffee.erb.
Rails will process the file extensions from right to left. Meaning right now, your file is treated first as coffeescript, then as ruby, and finally as javascript. It looks like you want to make the ruby substitutions first, then parse the coffeescript into javascript, so that would be menu.js.coffee.erb
First of all, you should change file name from menu.js.erb.coffee to menu.js.coffee.erb and you need configuration file as follow, which is a contribution by cervinka on coffee-rails issue #36
config/initializers/coffee_erb_handler.rb
ActionView::Template.register_template_handler 'coffee.erb', Coffee::Rails::TemplateHandler # without this there will be template not found error
class ActionView::PathResolver < ActionView::Resolver
EXTRACT_METHODS = %w{extract_handler_and_format_and_variant extract_handler_and_format} # name for rails 4.1 resp. 4.0
method_name = EXTRACT_METHODS.detect{|m| method_defined?(m) || private_method_defined?(m)}
raise 'unknown extract method name' if method_name.nil?
old_method_name = "old_#{method_name}"
alias_method old_method_name, method_name
define_method(method_name) do |path, default_formats|
self.send(old_method_name, path.gsub(/\.js\.coffee\.erb$/, '.js.coffee'), default_formats)
end
end
I'm using dropzone-rails to add dropzone to my Rails app. I'm using CarrierWave for image uploads which is working fine without Dropzone.
I'm getting an error when I drop an image onto my dropzone form. The form is located on the edit page of my "Canvas" model.
Form html
<%= form_for(#canvas, :html => { :class => 'dropzone', :id => 'awesomeDropzone' }) do |f| %>
<%= f.file_field :image %>
<%= f.submit %>
<% end %>
Dropzone JS call
Dropzone.options.awesomeDropzone = {
paramName: "canvas[image]", // The name that will be used to transfer the file
clickable: false
};
Console error:
GET http://localhost:3000/canvases/21/edit 500 (Internal Server Error)
canvases_controller.rb
def edit
#canvas = Canvas.find(params[:id])
end
def update
#canvas = Canvas.find(params[:id])
if #canvas.update_attributes(update_params)
redirect_to edit_canvas_path(#canvas)
else
render :edit
end
end
canvas.rb
mount_uploader :image, ImageUploader
Full log data
As per the error,
ActionView::MissingTemplate (Missing template canvases/edit, application/edit with {:locale=>[:en], :formats=>[:json], :handlers=>[:erb, :builder, :raw, :ruby, :jbuilder, :coffee]}. Searched in:
* "/Users/colmtuite/dev/design_tool/app/views"
):
You don't have edit view for canvases. Make sure that you have edit.html.erb file in app/views/canvases folder.
UPDATE
Also, I noticed that the request is going for Processing by CanvasesController#edit as JSON,
NOTE the format is JSON and not HTML. If you have edit.html.erb file and you want to render that particular view, make sure that you don't specify format as 'JSON' while calling edit action so by default format would be considered as HTML.
Change your update action as below:
def update
#canvas = Canvas.find(params[:id])
if #canvas.update_attributes(update_params)
redirect_to edit_canvas_path(#canvas, format: :html) ## Specify format as html
else
render :edit
end
end
dropzone using JSON format, not HTML, so
you can change controller to:
render nothing: true
or
render nothing: true, status: 200
Regards!