Web Programming examples

Google Maps,AngularJS

Ruby on Rails Tutorial follow/unfollow functionality with AngularJS

1)Rails route

$ vi config/routes.rb

  match '/app/relationships', to: 'relationships#create',  via: 'post'
  match '/app/relationships', to: 'relationships#destroy', via: 'delete'

2)Rails controller

$ vi app/controllers/relationships_controller.rb

class RelationshipsController < ApplicationController
  before_action :signed_in_user

  def create
    remember_token = User.encrypt(cookies[:remember_token])
    current_user ||= User.find_by(remember_token: remember_token)
    @user = User.find(user_params[:id])
    current_user.follow!(@user)
    head :no_content
  end

  def destroy
    remember_token = User.encrypt(cookies[:remember_token])
    current_user ||= User.find_by(remember_token: remember_token)
    @user = User.find(user_params[:id])
    current_user.unfollow!(@user)
    head :no_content
  end

  private
    def user_params
      params.permit(:id)
    end
    def signed_in_user
      remember_token = User.encrypt(cookies[:remember_token])
      current_user ||= User.find_by(remember_token: remember_token)
      if current_user.nil?
        render status: :unauthorized
      end
    end
end

3)AngularJS "relationshipsResource" service

$ vi app/assets/javascripts/mymodule.js.erb

myModule.factory("relationshipsResource", function($resource) {
  return $resource("/app/relationships",{},
    {
      'create':  { method: 'POST' },
      'destroy': { method: 'DELETE' }
    }
  );
});

4)AngularJS controller

$ vi app/assets/javascripts/mymodule.js.erb

myModule.controller("UsersShowCtrl", function($scope, $routeParams, userResource, flashService, $filter, micropostsResource, $q, sessionResource, relationshipsResource) {
.....
  $scope.follow = function(id) {
    function success(response) {
      $scope.flg_unfollow = true;
      sessionResource.current_user({}, function(response) {
        flashService.setUser(response);
      });
      $scope.$emit("$routeChangeSuccess");
    }
    function failure(response) {
      console.log("follow error");
    }
    var user_data = {
      id: id
    };
    relationshipsResource.create(user_data, success, failure);
  };

  $scope.unfollow = function(id) {
    relationshipsResource.destroy({ id: id }, function(response) {
      $scope.flg_unfollow = false;
      sessionResource.current_user({}, function(response) {
        flashService.setUser(response);
      });
      $scope.$emit("$routeChangeSuccess");
    });
  };

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.