diff --git a/app/assets/javascripts/angularjs/likes.js.coffee b/app/assets/javascripts/angularjs/likes.js.coffee index 38f5e43..78d1fda 100644 --- a/app/assets/javascripts/angularjs/likes.js.coffee +++ b/app/assets/javascripts/angularjs/likes.js.coffee @@ -1,28 +1,37 @@ @app.controller 'LikesController', ($scope, $http, $location, $cookies)-> url = $location.absUrl() + "/likes" - $scope.count = 0 - - $scope.get_count = -> - $http.get url - .success (res)-> - $scope.count = res.count - - $scope.get_count() + $http.get url + .success (res)-> + $scope.count = res.count $scope.like = $cookies.like + if $scope.like + $http + url: $location.absUrl() + "/likes/#{$scope.like}/is_liked" + method: 'GET' + .success (res)-> + if res == 'true' + $scope.is_liked = true + else + $scope.is_liked = false + else + $scope.is_liked = false + $scope.submit = -> $http.post url .success (res)-> if res.success $scope.like = $cookies.like = res.id $scope.count = res.count + $scope.is_liked = true $scope.cancel = -> $http.delete url + "/" + $scope.like .success (res)-> $scope.count = res.count + $scope.is_liked = false # anyway, clear cookie delete $cookies["like"] $scope.like = null diff --git a/app/controllers/likes_controller.rb b/app/controllers/likes_controller.rb index e36a2ac..32b9f99 100644 --- a/app/controllers/likes_controller.rb +++ b/app/controllers/likes_controller.rb @@ -6,6 +6,15 @@ class LikesController < ApplicationController render :json=> { success: true, count: post.liked_count } end + def is_liked + post = Post.find( params[:blog_id] ) + if post.likes.where(id: params[:id]).first + render text: true + else + render text: false + end + end + def create post = Post.find( params[:blog_id] ) like = Like.new diff --git a/app/views/blogs/_post.html.slim b/app/views/blogs/_post.html.slim index 010c5e9..b68193d 100644 --- a/app/views/blogs/_post.html.slim +++ b/app/views/blogs/_post.html.slim @@ -13,9 +13,9 @@ p.ptag | 发表于: span #{format_date(post.created_at)} p ng-controller="LikesController" - button.like-button ng-show="! like " ng-click="submit()" + button.like-button ng-show="! is_liked " ng-click="submit()" |{{ count }} span Like - button.like-button ng-show=" like " ng-click="cancel()" + button.like-button ng-show=" is_liked " ng-click="cancel()" |{{ count }} span Liked diff --git a/config/routes.rb b/config/routes.rb index fef43d1..45f79a6 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -6,7 +6,11 @@ WBlog::Application.routes.draw do get :rss end resources :comments, only: [:index, :create] - resources :likes, only: [:index, :create, :destroy] + resources :likes, only: [:index, :create, :destroy] do + member do + get :is_liked + end + end end