Rails 3 Ajax not working - ajax

I'm new to rails and ajax so I'm experimenting by building a simple app. I created a simple to do app with User and Tasks (user has many tasks). Using Devise to handle the authentication. I set up the task CRUD and implemented best_in_place (in place editing gem) and got it to work. What I wanted to do next is add ajax create and delete following some example resources such as creating a 100% ajax CRUD. After setting up all the necessary code for the create and destroy in tasks_controller, I'm getting DELETE http://localhost:3000/tasks/26 500 (Internal Server Error) as seen in the firebug console log. These are the errors printed in the console in firebug:
DELETE http://localhost:3000/tasks/26 500 (Internal Server Error)
jQuery.ajaxTransport.send
jQuery.extend.ajax
$.rails.rails.ajax
$.rails.rails.handleRemote
(anonymous function)
jQuery.event.dispatch
jQuery.event.add.elemData.handle.eventHandle
when the destroy link is clicked and same with create. The task got deleted and created after refresh but the ajax is just not working. I spent some time trying to figure out what's wrong but don't have any luck yet so I'm hoping I can get some help here while I keep digging into it. Below are my setups:
First the controller code:
def destroy
#task = current_user.tasks.find(params[:id])
#task.destroy
flash[:notice] = "Successfully destroyed post."
respond_to do |format|
format.html { }
format.js { }
end
end
def create
#task = current_user.tasks.build(params[:task])
respond_with(#task) do |format|
if #task.save
flash[:notice] = "Task was created successfully!"
respond_to do |format|
format.html { redirect_to tasks_url }
format.xml { render :xml => #task }
format.json { render :json => #task}
format.js
end
else
format.html { render :action => :new }
format.js
end
end
end
The task list partial to display the task list and delete
<table>
<% #tasks.each do |task| %>
<tr>
<td><%= best_in_place task, :detail %></td>
<!-- <p><%= best_in_place task, :completed, type: :checkbox %></p> -->
<td><%= link_to "Destroy", task, :confirm => 'Are you sure?', :method => :delete, :remote => true, :id=>'delete' %></td>
</tr>
<% end %>
</table>
The create form (without the other view stuff):
true) do |f| %>
<%= f.label :detail %>
<%= f.text_field :detail %>
<%= f.submit %> <% end %>
This is the javascript tag for application.html.erb (include jquery.js, jquery.ujs, application.js and other not so related js files):
Lastly I'm just trying to call an alert inside destroy.js.erb and with create.js.erb:
alert("Task was deleted");
Again, the crud is working normally when refreshed, it feels like the destroy.js.erb and create.js.erb is not linked somehow. I appreciated if you can provide a few hints.
Here is the error from the console after hitting delete:
ActionView::Template::Error (You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.each):
1:
2: <table>
3: <% #tasks.each do |task| %>
4:
5: <tr>
6: <td><%= best_in_place task, :detail %></td>
app/views/tasks/_tasks.html.erb:3:in `_app_views_tasks__tasks_html_erb___1747031968745406293_70257861453000'
app/views/tasks/destroy.js.erb:4:in `_app_views_tasks_destroy_js_erb___3673072470672404292_70257861472560'

It looks as though you have a syntax error in the destroy action. I think you're missing an end for the respond_to block.

Related

Routing issue on Nested Resource Custom Update Method

Im Building out a Rails app in Rails 4 Ruby 2
Background:
I have built a custom Method in a controller that allows me to update a table by button click.
I had some help building out the button, however it only updates the first id, in the nested element.
I am looking for said button when pushed to target only the line item its sitting in.
The button/link:
<%= link_to "Remove Unit", [#call, responding], class: 'btn btn-danger btn-sm', method: :delete, confirm: "Are you sure you want to remove this unit?" %><%= link_to "Responding", unit_responding_update_call_responding_path(call_id: #call.id, id: #respondings.first.id), method: :patch %>
this button is displayed with in a <%= #respondings.each do |responding| %> and should populate with each line item that is added, so that it can update that record when pushed.
the controller action is:
def unit_responding_update
#call = Call.find(params[:call_id])
#responding = Responding.find(params[:id])
#responding.responding_tme = DateTime.now
#responding.responding = "true"
#responding.on_scene = "false"
#responding.clear = "false"
#responding.save!
respond_to do |format|
if #responding.save
format.html { redirect_to #call, notice: "Responding time successfully updated." }
else
format.html { render action: 'edit' }
end
end
end
Routes.rb is:
resources :calls do
resources :respondings, except: [:index], controller: 'calls/respondings' do
member do
patch :unit_responding_update
end
end
resources :pings, except: [:index], controller: 'calls/pings'
resources :agencies, except: [:index], controller: 'calls/agencies'
resources :incidents, except: [:index], controller: 'calls/incidents'
resources :complainants, except: [:index], controller: 'calls/complainants'
end
end
And finally the output for Rake Routes for the custom action is:
unit_responding_update_call_responding PATCH /calls/:call_id/respondings/:id/unit_responding_update(.:format) calls/respondings#unit_responding_update
I know its probably only a small problem, ive looked at similar StackOverflow Questions, treehouse forums and code academy resources but can not for the life of me sort this one out..
Thanks in advance for your assistance. Please lte me know if you require anything further for information.
however it only updates the first id, in the nested element.
this is caused by
<%= link_to "Responding", unit_responding_update_call_responding_path(call_id: #call.id, id: #respondings.first.id), method: :patch %>
As this button is displayed with in a <%= #respondings.each do |responding| %>, replace with
<%= link_to "Responding", unit_responding_update_call_responding_path(call_id: #call.id, id: responding.id), method: :patch %>

How to pass param from 1 controller to another

I want to pass param from the following link in the view of Client controller
and the hash is #client, I want to pass #client.user_id, if i put (:id => #client.user_id) I am not able the get :id in the other controller Estate where I want to pass this param. What should I do ? Is there a way to do it ?(Two controllers are Client and Estate, I want to pass param from Client view to the Estate controllers create method. There is no nesting of resources here!)
<%= link_to "New Property", new_estate_path(:key => #client.first.user_id) %>
create action
def create
# #estate = Estate.new(params[:estate])
if current_user.Company.nil?
#estate = current_user.estates.build(params[:estate])
else
serve = User.find(params[:key])
debugger
#estate = serve.estates.build(params[:estate])
##estate.user_id = user_id
debugger
end
respond_to do |format|
if #estate.save
if #estate.Mgmt.nil?
EstateMailer.company_confirmation(#estate).deliver
end
format.html { redirect_to #estate, notice: 'Estate was successfully created.' }
format.json { render json: #estate, status: :created, location: #estate }
else
format.html { render action: "new" }
format.json { render json: #estate.errors, status: :unprocessable_entity }
end
end
end
The code you pasted here should work:
<%= link_to "New Property", new_estate_path(:id => #client.user_id) %>
I think the problem is, you are expecting the params in create method but where as it actually goes to new method.
If you are looking for the create method. You can do
<%= link_to "New Property", estates_path(:id => #client.user_id), :method => :post %>
But that is not the right approach to use for POST actions. The right solution would be to use button_to.
<%= button_to "New Property", estates_path(:id => #client.user_id), :method => :post %>
link_to defaults to GET and button_to defaults to POST, as those are their primary usages. You can override :method if you want them to perform other action than their default.
Simply do this
<%= link_to "New Property", new_estate_path(user_id: #client.user_id) %>
In your controller:
params[:user_id]
You problem is that the create action is a POST not a GET. The link_to will only allow GET actions.
I made class variable in the controller outside all the actions.
##key, and in the new action assigned ##key the user_id that was coming through the params, and this ##key in the create action. I don't know if its the right way to do it. But it worked like a charm !

Remote Form Renders as HTML instead of JS

I have a simple form:
<%= form_for [current_user, #bookcase], :id => "shelf_update_form", :remote => true, :html => { :multipart => true} do |f| %>
<input id="bookcase_image" class="file" type="file" name="bookcase[image]" size="13">
<% end %>
That automatically uploads when a file has been selected:
$("#shelf_update_form").change(function() {
$("#shelf_update_form").submit();
});
I want the update action to render js view, but by default it renders html instead. I try forcing it to render js like so:
respond_to do |format|
format.js
end
But then I get this error:
NetworkError: 406 Not Acceptable
Even then, my log reports:
Processing by BookcasesController#update as HTML
How can I get it to process as JS instead?
UPDATE:
The view:
triggerAjaxHistory("<%= #href %>", false);
I get the same results with a more generic view, too:
alert("I work now!")
In the controller, do
respond_to do |format|
format.js if request.xhr?
end
Is your view named as .js.erb?
Can you check using firebug in your browser what exactly you are getting as the response? Turn on net logging and look at the response.
Also do you have the following in your layout?
<%= javascript_include_tag :defaults %>
<%= csrf_meta_tag %>
Can you put in logger.info whatever_message commands to make sure you the controller action executes and you go into the correct view?
What happens if you specify the js format specifically in the controller as
class UserController < ApplicationController
respond_to :js, :only => :update, :layout => 'false`
What happens if you specify the format in form_for as :format => :js
Is your form nested within another form?

RoutingError when using jQuery UI tabs with ajax

I'm getting ActionController::RoutingError in Profiles#show when I click a link to render a layout as part of my implementation of jQuery UI tabs. Here's my link_to:
<%= link_to "Messages", :controller => 'profiles', :action => 'profile_messages', :remote => true %>
My ProfilesController:
def profile_messages
#messages = User.find(#profile.user_id).messages
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => #messages }
end
end
My profile_messages erb layout:
<div id="tabs-2">
<% for message in #user.messages %>
<div class="message-1">
</div>
<% end %>
</div><!-- end messages -->
Routes.rb:
resources :messages do
get "messages/profile" => :profile_messages
resources :responses
end
What I want to happen is: when you click the link created by my link_to, the layout in profile_messages.html.erb shows and loads the messages in that specific layout. What's going on here?
UPDATE: Adding the new line in Routes.rb gives me a new route:
message_messages_profile GET /messages/:message_id/messages/profile(.:format) {:action=>"profile_messages", :controller=>"messages"}
So I tried this in my Profiles show.html.erb I put:
<li><%= link_to "Messages", message_messages_profile_path, :remote => true %></li>
This gives me a RoutingError in Profiles#show -- No route matches {:action=>"profile_messages", :controller=>"messages"}. Even when I add the following into my MessagesController:
def profile_messages
#message = #user.messages.find(params[:user_id])
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => #messages }
end
end
get "messages/profile" => "messages#profile_messages", :as => profile_messages
resource :messages do
resource :responses
end
You don't have a route for that controller action. Rails doesn't map ":controller/:action/:id" by default any more. You can also just enable that route if you want. You could be able to reference this via profile_messages_path.
It's assuming 'show' is actually an id for messages here I think. The default routes for a resource are listed here: http://guides.rubyonrails.org/routing.html#crud-verbs-and-actions. Make sure you list your routes first!
resource :messages do
collection do
get :profile_messages
end
end
in your view
<li><%= link_to "Messages", "/messages/profile_messages", :remote => true %></li>
Thanks to the combined efforts of folks here on SO I was able to get this to work. Check out these questions for more code:
Exclude application layout in Rails 3 div
Rails 3 jQuery UI Tabs issue loading with Ajax

Rails 3.1 Ajax forms don't show validation

I'm using updated pre Ruby on Rails on Ruby 1.9.2 (with rvm), and made a new test application with
$ rails generate scaffold Project name:string
and
class Project < ActiveRecord::Base
validates_presence_of :name
end
I change
<%= form_for #project do |f| %>
to
<%= form_for #project, :remote => true do |f| %>
I can now still (without any changes in the controller) add new items to the project. If I try to add with empty in the name field, it will not add anything (validates_presence_of :name stops this), but I don't get any validation error messages. I have tried the same on an application converted from 3.0 I'm working on with same results. Here I had:
class KursController < ApplicationController
# GET /kurs
# GET /kurs.xml
respond_to :js, :html
and:
def update
#kur = Kur.find(params[:id])
#kur.update_attributes(params[:kur])
flash[:notice] = "Lagret" if #kur.save
respond_with( #kur, :layout => !request.xhr? )
end
In 3.1 I get no validation error messages. Is this because of a bug in Ruby on Rails 3.1 or something I should do different?
You are missing to call these errors. Do something like this:
<%= form_for #project do |f| %>
<%= render :partial => 'my_error_messages_for', :locals => {:collection => #project} %>
In "_my_error_messages_for.html.erb":
<% if collection.errors.any? %>
<ul>
<% collection.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
<% end %>
You can create a helper for this work.
I don't believe that Ruby on Rails will automatically include the partial that you've requested. You'll need to add some JavaScript code to get it to work correctly. Something like this I imagine:
// Application.js
$("form").bind("ajax:success", function (event, data, status, xhr) {
$(event.target).replaceWith(data);
});

Resources