Rails 3 UJS - controller gets called twice by link

2019-01-08 10:03发布

I have a weird problem where JQuery is creating two AJAX requests for a link_to method. I am developing a Rails 3 app with JQuery for UJS. I have a toggle link which toggles between 'Follow' and 'Unfollow'

My link is rendered as below:

<span id="follow_link">
  <a href="/tfollow_artist?id=8103103" data-method="post" data-remote="true" id="follow_artist" rel="nofollow">Unfollow</a>
</span>

and my controller is setup so:

def tfollow_artist
  @artist = Artist.find(params[:id])
  if current_user.following?(@artist) 
    current_user.stop_following(@artist)
  else 
    current_user.follow(@artist)
  end
 end

which finally renders a js as:

 $('#follow_link').html('<%= escape_javascript(render :partial => "follow") %>');

Which essentially replaces html contents of the '<span id="follow_link">...</span> with the same URL only with the text being different. For example, above will now be rendered as:

<span id="follow_link">
  <a href="/tfollow_artist?id=8103103" data-method="post" data-remote="true" id="follow_artist" rel="nofollow">Follow</a>
</span>

However this is somehow causing JQuery to make two AJAX requests.

Can any one see what is wrong here?

I am using 'jquery-rails' gem which is copying the latest jquery-ujs file to my app. JQuery version is 1.4.3

11条回答
▲ chillily
2楼-- · 2019-01-08 10:40

I had simmilar issue. Running following rake tasks resolved my problem.

rake tmp:clear
rake assets:clean
查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-01-08 10:48

I think what is happening is that your JavaScript is not stopping the link from being executed by the browser. So you get the AJAX request then the browser request.

There is an explanation and solution for this in Rails Cast 174. Text explanation here, about 3/4 of the page down.

查看更多
ら.Afraid
4楼-- · 2019-01-08 10:48

Also for me the same problem: twice XMLHttpRequest on a link_to ... :remote => "true"

I've solved, in

locals/application.rb :

by commenting

// config.assets.paths << Rails.root.join('vendor','assets','stylesheets','javascripts')

and uncomment

config.action_view.javascript_expansions[:defaults] = %w(jquery jquery-ui application)

then I forgot to do after my last git pull. I hope help someone.

查看更多
淡お忘
5楼-- · 2019-01-08 10:50

I had the same issue, fixed by commenting this line

\#config.assets.debug = true

in development mode

查看更多
forever°为你锁心
6楼-- · 2019-01-08 10:50

If you are not able to find out where the ujs file is loaded twice, simply copy this code into rails.js / application.js (preferably not here)

var alreadyInitialized = function() {
    var events = $(document).data('events');
    return events.click && $.grep(events.click, function(e) { return e.namespace === 'rails'; }).length;
    }

if ( alreadyInitialized() ) {
    $.error('jquery-ujs has already been loaded!');
}
查看更多
登录 后发表回答