轨道上的Ajax 4

rob*_*obb 4 ajax jquery ruby-on-rails-4

我有一个应用程序,允许用户喜欢一个帖子.当有人喜欢这个帖子时,帖子请求有效,但除非我刷新页面,否则视图不会更新.我坚持这个.这是我到目前为止:

使用Javascript

$('.favorite').on('click', function() {
  var $heart = $(this).find('.fa');
  $heart.removeClass('fa-heart-o').addClass('fa-heart');
  // POST request to server to create favorite in db
  $.post('/favorites', {
    favorite: { post_id: $(this).attr('data-id') }
  },
  function(data) {
    console.log(data);
  });
});
Run Code Online (Sandbox Code Playgroud)

控制器

def create
  post = Post.find_by_id(favorite_params[:post_id])
  if current_user.favorite_posts.include? post
    render json: {}, status: :bad_request
  else
    @favorite = current_user.favorites.new(favorite_params)
    if @favorite.save
      render json: @favorite
    else
      render json: { errors: @favorite.errors.full_messages }, status: :unprocessable_entity
  end
end
Run Code Online (Sandbox Code Playgroud)

结束

这是观点

<% if current_user.favorite_posts.include? post %>
  <span class="fa fa-heart"> <%= post.favorites.count %></span>
<% else %>
  <span class="fa fa-heart-o"> <%= post.favorites.count %></span>
<% end %>
Run Code Online (Sandbox Code Playgroud)

任何帮助表示赞赏.谢谢.

Arv*_*ind 6

做这个:-

var new_count;
new_count = function() {
  # your script
};



$(document).ready(new_count);
$(document).on('page:load', new_count);
Run Code Online (Sandbox Code Playgroud)

这个问题似乎是由于turbolink checkthis