小编rob*_*obb的帖子

轨道上的Ajax 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> …
Run Code Online (Sandbox Code Playgroud)

ajax jquery ruby-on-rails-4

4
推荐指数
1
解决办法
134
查看次数

标签 统计

ajax ×1

jquery ×1

ruby-on-rails-4 ×1