3

I followed the railscast tutorial , but I found I can not load the "saved tokens".

I think the problem is that when click 'edit' link (created by scaffold),

it didn't trigger the preload function, how do you fix the problems in Rails 4

enter image description here View page

  .form-inputs
    = f.input :name
    = f.input :content
    = f.text_field :user_tokens, data: {load: @article.users}

My coffeescript

$(document).ready -> 
  $('#article_user_tokens').tokenInput '/users.json',
    theme: 'facebook',
    prePopulate: $('#article_user_tokens').data('load')

Require the css and js file

 *= require token-input-facebook
 //= require jquery.tokeninput

I fix the bug by this solution, use the ready page:load

But I can not understand, why it works

$(document).on "ready page:load", ->
  $('#article_user_tokens').tokenInput '/users.json',
    theme: 'facebook',
    prePopulate: $('#article_user_tokens').data('load')
newBike
  • 14,385
  • 29
  • 109
  • 192
  • Possible duplicate of [Rails 4: how to use $(document).ready() with turbo-links](http://stackoverflow.com/questions/18770517/rails-4-how-to-use-document-ready-with-turbo-links) – Yuri Ghensev Jan 31 '17 at 02:45

1 Answers1

1

When Turbolinks is enabled, Rails uses Ajax to load only the elements of a page that have changed, rather than loading an entire new page. For this reason, there is often no page load from the standpoint of jQuery $(document).ready. See here for a great post on using .js in Rails 4.

$(document).on 'ready, page:change' is frequently used as the substitute for $(document).ready on pages which are not fully reloading because of Turbolinks in Rails 4. I think if you switch to that your problem should go away.

Your syntax may be a little off as well with $(document).on "ready page:load". There have been other reports of problems when you are missing a comma between ready and page.

Community
  • 1
  • 1