Hi, guys,
I’m in the midst of moving an app from rails 2.3.8 to rails 3.0.9.
Sadly, rails 3 no longer has javascript generators and I’m now forced
to do more javascript.
For my project, I have selected jQuery as the javascript framework for
my rails 3.0.9 app.
What I have done to have my app’s deletion link (for each item)
trigger an alert box when the deletion process is completed:
- installed jquery-rails gem, deleted the public/javascript/rails.js
file - added the line, “gem ‘jquery-rails’, ‘>= 0.2.6’” to my Gemfile, ran
“rails generate jquery:install” - set up the controller action, destroy to respond by giving a json
object when it’s being called by ajax
DELETE /parts/1
DELETE /parts/1.xml
def destroy
@part = Part.find(params[:id])
@part.destroy
respond_to do |format|
format.html { redirect_to(parts_url) }
format.xml { head :ok }
format.js {
render :json => {:name => 'John'}
}
end
end
- added the following to application.js
// Place your application-specific JavaScript functions and classes
here
// This file is automatically included by
javascript_include_tag :defaults
$(document).ready(function () {
function(e, data, textStatus, jqXHR){
alert(data.name + ’ has been deleted’);
$(‘a[data-method=“delete”]’).css(“color”, “red”);
});
})
- the view, app/views/parts/index.html.erb has deletion links for
each part item:
<% if @parts != nil %>
<% @parts.each do |part| %>
<tr>
<td>
<%= part.id %>
</td>
<td><%= link_to(part.title, part) %> </td>
<td><%= link_to 'Preview', part %></td>
<td><%= link_to 'Update', edit_part_path(part) %></td>
<td>
<%=
link_to 'Delete',
part_path(part.id),
'data-method' => 'delete',
'data-confirm' => 'Are you sure?',
'data-remote' => 'true',
'class' => 'delete_part'
%>
</td>
</tr>
<% end %>
</table>
<hr>
<% end %>
When I run “script/rails server”
Pre: I turn on Firebug on Firefox
- I clicked on the “delete” link on an entry. Confirm dialog box pops
up. I click “yes” - I looked at the “Net” tab and I see the DELETE request. Clicked on
the DELETE tab - Looked at the header and json sub tabs and I see the expected data
that I defined to return from the destroy action in the parts
controller (above)
What am I missing?
The json data gets returned but somehow, jquery is not intercepting
it
Is the ajax callback that I put in application.js errorneous/
incomplete?
Any good references (that work) with rails 3 UJS (ajax)?
My references were:
1)
2) http://rails3stuff.posterous.com/#!/59899595
3) Ajax Events | jQuery API Documentation
4) #205 Unobtrusive Javascript - RailsCasts
5 )
Unobtrusive JavaScript in Rails 3 — Simone Carletti
6) Redirecting...
7)
RailsDog.com is for sale | HugeDomains
What I have also tried:
Even tried defining app/views/parts/destroy.js.erb - with a simple,
alert(’ Calling destroy.js.erb ') - Does not work
Please.
Thank you
Id | Title | Brand new? | Manage |
---|