server error with uploadify in ruby on rails 3.1 - ruby-on-rails-3

I'm trying to upload a video using uploadify and paperclip on rail 3.1
When i upload a video with uploadify, the server returns an 500 error.
The development.log says:
Started POST "/videos" for 127.0.0.1 at Tue Oct 04 14:46:05 +0200 2011
Processing by VideosController#create as HTML
Parameters: {"Filename"=>"prova.mov", "folder"=>"/public",...}
WARNING: Can't verify CSRF token authenticity
#<Video id: nil, source_content_type: nil, source_file_name: nil, source_file_size:nil, state: nil, created_at: nil, updated_at: nil>
[paperclip] Saving attachments.
Completed 500 Internal Server Error in 29ms
ActionView::MissingTemplate (Missing template videos/create, application/create with {:locale=>[:en, :en], :handlers=>[:builder, :coffee, :erb], :formats=>[:html]}. Searched in:
* "($mypath)/workspace/Video_Api/app/views"):app/controllers/videos_controller.rb:48:in `create'.
This is my controller:
def create
logger.info(params.inspect)
#video = Video.new(params[:video])
logger.info(#video.inspect)
respond_to do |format|
if #video.save
format.html
format.json { render :json => #video, :status => :created, :location => #video }
else
format.html { render :action => "new" }
format.json { render :json => #video.errors, :status => :unprocessable_entity }
end
end
end
And this is my uploader:
<input id="upload" type="file" name="upload" />
<!--div class="button" id="send_button">SEND FILE</div -->
</div>
<script>
<%- session_key = Rails.application.config.session_options[:key] -%>
$('#upload').uploadify({
'uploader' : 'uploadify.swf',
'script' : '/videos',
'cancelImg' : 'images/cancel.png',
'folder' : '/public',
'buttonText' : 'Add video!',
'multi' : true,
'auto' : true,
'scriptData' : {"<%= key = Rails.application.config.session_options[:key] %>" :"<%= cookies[key] %>",
"<%= request_forgery_protection_token %>" : "<%= form_authenticity_token %>",
},
onError : function (event, id, fileObj, errorObj) {
alert("error: " + errorObj.info);
}
});
Any ideas?

The error is pretty straightforward -- it is saying that you are missing a template to render videos/create -- if you're trying to render HTML here, you'll need to create this template. If you're expecting your JSON response instead, you need to figure out why that isn't being triggered. Changing the 'script' parameter to be '/videos.json' should take care of that, although it might be smarter to use the Rails helper url_for.

Related

How config url in Kaminari pagination? '.json' appended automatically

Load table with Kaminari pagination using AJAX.
The pagination itself is using AJAX as well.
In my controller:
def update_user_list
modal = render_to_string('tables/_user_table', :layout => false, :formats=>[:html]).html_safe
data = {
:table => modal
}
respond_to do |format|
format.json { render :json => data }
end
end
In tables/_user_table
# Table part and content notrelated
<%= paginate #users, :params => {:controller => 'product', :action => 'more_users'}, :remote => true, :theme => 'twitter-bootstrap-3' %>
The response JSON of update_user_list looks like:
{
table=" // the table part
// the pagination part shows as follows
<li class="page">3</li>
<li class="page">4
"
}
What I want is to remove ".json" in the url.
If I just render tables/_user_table without AJAX, not in a JSON object, it doesn't have ".json" in the url.
version:
rails: 3.2.17
kaminari: 0.13.0
bootstrap-kaminari-views: 0.0.3
Find the problem. It's actually not included in the question.
$.ajax({
url: '<%= user_product_index_url %>.json',
success: function(data) {
// not important......
});
remove ".json" here solve the problem...

Ruby NoMethodError - undefined method `blah_url' for BlahController

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

Rails: nested resources and routing errors

I've got a Template model, and a Doc model. They're nested resources, with the Templates being the parent, thus:
resources :templates do
get "/documents/lock/:id" => "docs#lock", :as => :lock_doc
get "/documents/unlock/:id" => "docs#unlock", :as => :unlock_doc
get "/documents/pdf/:id" => "docs#pdf", :as => :pdf_doc
resources :docs, :path => :documents
end
That part, I think, all works fine. When I try to submit the form for creating a doc the record exists but I get routing errors, thus:
ActionController::RoutingError (No route matches {:action=>"edit", :controller=>"docs", :template_id=>nil, :id=>#<Doc id: 2, user_id: "admin", cover: "1209hpnl", message: "The world economic outlook is improving, albeit slo...", created_at: "2013-01-07 03:54:05", updated_at: "2013-01-07 03:54:05", issue_code: "1209hpnl", title: "January 2013", locked: nil, retired: "active", template: nil>}):
app/controllers/docs_controller.rb:134:in `block (2 levels) in create'
app/controllers/docs_controller.rb:132:in `create'
The lines correspond to the create method:
def create
#doc = Doc.new(params[:doc])
respond_to do |format|
if #doc.save
format.html { redirect_to share_url(#doc), notice: "Saved. You may from here #{view_context.link_to('edit', edit_template_doc_url(#doc))} it further, #{view_context.link_to('finalise', template_lock_doc_url(#doc))} it, or return #{view_context.link_to('home', root_url)}.".html_safe }
format.json { render json: #doc, status: :created, location: #doc }
else
format.html { render action: "new" }
format.json { render json: #doc.errors, status: :unprocessable_entity }
end
end
end
I think the problem lies somewhere in here, but I can't for the life of me figure it out.
Cheers for any help!
EDIT: with rake routes
template_lock_doc GET /templates/:template_id/documents/lock/:id(.:format) docs#lock
template_unlock_doc GET /templates/:template_id/documents/unlock/:id(.:format) docs#unlock
template_pdf_doc GET /templates/:template_id/documents/pdf/:id(.:format) docs#pdf
template_docs GET /templates/:template_id/documents(.:format) docs#index
POST /templates/:template_id/documents(.:format) docs#create
new_template_doc GET /templates/:template_id/documents/new(.:format) docs#new
edit_template_doc GET /templates/:template_id/documents/:id/edit(.:format) docs#edit
template_doc GET /templates/:template_id/documents/:id(.:format) docs#show
PUT /templates/:template_id/documents/:id(.:format) docs#update
DELETE /templates/:template_id/documents/:id(.:format) docs#destroy
templates GET /templates(.:format) templates#index
POST /templates(.:format) templates#create
new_template GET /templates/new(.:format) templates#new
edit_template GET /templates/:id/edit(.:format) templates#edit
template GET /templates/:id(.:format) templates#show
PUT /templates/:id(.:format) templates#update
DELETE /templates/:id(.:format) templates#destroy
The problem is in your call to edit_template_doc_url(#doc) inside the notice string. You need to supply the template as well, like this:
edit_template_doc_url(params[:template_id], #doc)

Rails render works in console but does not load page

My goal is to render html from an AJAX call. Changing the dataType to 'html' in my AJAX call seemed to work in that on my console it happily claims that the render was successful:
Rendered admin/articles/show.html.erb within layouts/application (108.1ms)
Completed 200 OK in 185ms (Views: 112.6ms | ActiveRecord: 2.8ms)
but the page does not change.
Here's some code:
View:
<span id='show' class="ui-icon ui-icon-extlink" article_id=<%=article.ID %> onmouseover="this.style.cursor='pointer'"></span>
jquery:
$('#show').live("click",function(evt){
evt.preventDefault();
var article_id=$(this).attr("article_id");
$.ajax({
success : null,
type : 'GET',
url : '/admin/articles/show',
dataType : 'html',
data: {
id: article_id
},
});
});
and my controller:
def show
#article = Article.find(params[:id])
respond_to do |format|
format.html
format.xml { render :xml => #article }
end
end
routes.rb
match 'articles/show' => 'articles#show', :via => :get
I know it's an odd request to want to render html from AJAX but it's the easiest way that I can think to have a clickable link contained in a span tag.
Using Rails 3.0.1, Ruby 1.9.2 and JQuery
usually ajax request ha js type,if you can change type to js these changes will works
controller
def show
#article = Article.find(params[:id])
respond_to do |format|
format.html
format.js
format.xml { render :xml => #article }
end
end
then in app/views/articles/show.js.erb write javascript code to update page content like
$("#yourDiv1").html("blah blah");
$("#yourDiv2").html("whatever");
and following approach will work for both html and JS
$.ajax({
success : null,
type : 'GET',
url : '/admin/articles/show',
dataType : 'html',
data: {
id: article_id
},
}).done(function( html ) {
$("#yourDIv").html(html);
});

406 Not Acceptable - xhr image upload to rails

I am trying to upload an image from iPhone to my working rails application that uses Carrierwave for processing. Do I need to account for the CSRF authenticity token that rails requires?
I have the following in my Titanium app.js file, taken pretty much from their Snapost example code:
xhr.open('POST','http://myapp.com/foos/1/bars');
xhr.send({media:originalImage});
My rails action is very simple:
def create
#bar = #foo.bars.build(params[:bar])
#bar.image = params[:file]
respond_to do |format|
if #bar.save
format.html { redirect_to(#foo, :notice => 'Bar was successfully created.') }
format.json { render :json => #bar, :status => :created }
fotmat.xml { render :xml => #bar, :status => :created }
else
format.html { render :action => "new" }
format.json { render :json => #bar.errors, :status => :unprocessable_entity }
format.xml { render :xml => #bar.errors, :status => :unprocessable_entity }
end
end
end
From my device, I get the 'xhr.onerror' alert describing a timeout when I attempt an upload. My server log is as follows:
Started POST "/foos/1/bars" for ###.###.#.### at 2011-05-01 17:01:33 -0500
Processing by BarsController#create as MULTIPART_FORM
Parameters: {"media"=#<ActionDispatch::Http::UploadedFile:0xabdd968 #original_filename="285050.jpg", #content_type="image/jpeg", #headers="Content-Disposition: form-data; name=\"media\"; filename=\"2
85050.jpg\"\r\nContent-Type: image/jpeg\r\n", #tempfile=#<File:/tmp/RackMultipart20110501-32635-olgooh>>, "foo_id"=>"1"}
^[[1m^[[36mSQL (1.9ms)^[[0m ^[[1mSHOW TABLES^[[0m
^[[1m^[[35mFoo Load (0.1ms)^[[0m SELECT foos.* FROM foos WHERE foos.id = 1 LIMIT 1
^[[1m^[[36mSQL (2.6ms)^[[0m ^[[1mBEGIN^[[0m
^[[1m^[[35mSQL (5.9ms)^[[0m ROLLBACK
Completed 406 Not Acceptable in 468ms
You are correct, it is the authenticity token (or lack there of) that is causing the problem. How do I ignore the authenticity token for specific actions in Rails? has more details on how to have it ignored. More details at http://api.rubyonrails.org/classes/ActionController/RequestForgeryProtection.html