简体   繁体   中英

jQuery in Rails 3 with “Beginning Rails 3”

I'm learning how to use Rails with "Beginning Rails 3" by Carneiro and Barazi. The end goal is to build a functional blog. This book is oriented towards Rails 3.0 and I'm running 3.2, so I am using jQuery while they are using Prototype for Ajax stuff. At one point they ask you to switch from Processing to jQuery, which I skipped. Later, when they start to use js code, they have you put this code

<%= render @article %>
<h3>Comments</h3>
<div id="comments">
  <%= render @article.comments %>
</div>
<%= link_to "new comment", new_article_comment_path(@article, :format => :js), :remote => true, :id => 'new_comment_link' %>

into the "article" view, and this code

$("<%= escape_javascript render(:file => 'comments/new.html.erb') %>").insertAfter('#comments');
$('#new_comment_link').hide();

into a javscript file in the new_comment view that works when creating new comments. The idea is that when you display an article, it shows all of the comments and a link to create a new comment. When you click the link, it loads the new_comment fields from the new_comment view, instead of having them there all the time. However, when I load my blog and click the "new comment" link, nothing happens. I've tried following the instructions from the book (put in the jquery.min.js file, putting in a jQuery adaptor) but it doesn't seem to work (and shouldn't be put in to begin with, I think). Any ideas? Help would be much appreciated.

1) Have you included the jquery-rails gem? It helps wire jquery up to rails, and you don't need to manually add the jquery.min.js file yourself

2) Have you tried putting an alert in the javascript file to make sure it's running at all?

3) Have you checked your development log to see what's happening when it hits that new comment url to see what it says?

I've spent the last three days debugging a similar issue[1]:http://stackoverflow.com/questions/9666929/simple-rails-ajax-call-wont-process-as-js

First, Rails 3.2 uses a gem. Put it in your gemfile and run bundle install.

Second (as the page says) you'll need to make sure both included, though they were set by default: In app/assets/javascripts/application.js You should have

//= require jquery
//= require jquery_ujs

Note that jquery-ujs actually does much of the magic here.

Two things can break:

  1. Your controller may not receive the ajax request properly
  2. your response may not work

To see which is the case, look at your server output or log. Does it show that new_article_comment is being executed? And does it say "Processing ... as JS"?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM