Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I am using angularjs-rails-resource and I have set up a service. I have a table of leagues which belongs_to a user so the columns of the league table are id, name, and user_id. I am trying to pull out all the leagues for a specified user.

Here's the code. Every time I use it I am getting all the leagues returned. I am pretty sure I don't have the service defined correctly. Any help would be greatly appreciated.

league_service.js

'use strict';

/* Services */
var ffpServices = angular.module('ffpServices', ['rails']);
ffpServices.factory('League', ['railsResourceFactory', function (railsResourceFactory) {
    return railsResourceFactory({
        url: '/api/v1/leagues',
        name: 'league'
    }); }]);

leagues_controller.js

'use strict';

/* Controllers */
var ffpControllers = angular.module('ffpControllers', []);

ffpControllers.controller('LeagueCtrl', 
     function ($scope, $routeParams, League) {
     $scope.leagues = League.query({ user_id: $routeParams.userId });
     $scope.leagues.then(function (results) {
         $scope.leagues_data = []; 
         $scope.leagues_data = results; 
         $scope.lempty = false;

         if ($scope.leagues_data.length < 1) {
         $scope.lempty = true;
         }

     }, function (error) {
         console.log(error); 
     });
 });

leagues_controller.rb

class Api::V1::LeaguesController < ApplicationController
  respond_to :json

  def index
    @leagues = League.all
    render json: @leagues
  end

  def show
    @league = League.find(params[:id])
    render json: @league
  end

  def create
    @league = current_user.leagues.new(league_params)

    respond_to do |format|
      if @league.save
        format.json { head :created, location: league_path(@league) }
      else
        format.json { head :unprocessable_entity }
      end
    end
  end

  private

  def league_params
    params.require(:league).permit(:name)
  end
end
share|improve this question
    
please post your leagues_controller.rb –  Pavittar Gill Sep 20 at 6:07
    
I added the leagues_controller.rb. Thinking about it some more I'm guessing I need to create a new part of my api that returns the results I want since the angularjs-rails-resource seems to be just for wrapping up a rails resource and that's about it. –  Stephen Burke Sep 22 at 3:14
    
in your index action you are returning all the records, instead you should use the user_id in a where clause to filter it out by a particular user and return that League.where(user_id: params[:user_id]) –  Pavittar Gill Sep 24 at 3:38

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.