Проблема сериализации Rails 4 и Angularjs

У меня возникла проблема, когда я пытаюсь отправить объект json моему действию создания в контроллере rails. Переменные в моих параметрах интерпретируются как строка, а не объект json. Вот мой код.

Угловой контроллер

rsn.controller(
'NewTeamController', [
    '$scope', '$http',
    function($scope, $http) {
        // list of player son the team
        $scope.team = {name: '', league_id: '', players: []};

        // temp variables for adding a player
        $scope.player = {};

        $scope.addPlayer = function() {
            $scope.team.players.push($scope.player);

            $scope.player = {};

            console.log($scope.team);
        };

        $scope.saveTeam = function() {
            $http({method: 'POST', url: '/leagues/'+$scope.team.league_id+"/teams", params: {team: $scope.team}})
                .success(function(data, status, headers, config) {
                    console.log('It worked!');
                }
            );
        };

    }
]

);

Соответствующий код контроллера Rails

    class TeamsController < ApplicationController


  def create

    @team = Team.new(team_params)

    respond_to do |format|
      if @team.save
        format.html { redirect_to @team.league, notice: 'Team was successfully created.' }
        format.json { render action: 'show', status: :created, location: @team }
      else
        format.html { render action: 'new' }
        format.json { render json: @team.errors, status: :unprocessable_entity }
      end
    end

  end


    private
    # Use callbacks to share common setup or constraints between actions.
    def set_league
      @team = Team.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def team_params
      params.require(:team).permit(:name, :league_id)
    end
end

Когда я запускаю $scope.saveTeam(), я получаю сообщение об ошибке "undefined method `permit' for #" для вызова разрешения в функции team_params. На странице ошибки раздел параметров выглядит так:

{"team"=>"{\"name\":\"\",\"league_id\":6,\"players\":[{\"name\":\"Dan\",\"email\":\"[email protected]\"}]}", "league_id"=>"6"}

Кто-нибудь знает, почему мои параметры, переданные из angular, интерпретируются как строка?


person Dan    schedule 29.01.2014    source источник


Ответы (2)


Я нашел ответ. Я неправильно делал http-пост из angular. Ниже приведен код $http, который работал правильно.

$http.post('/leagues/'+$scope.team.league_id+"/teams.json", {team: $scope.team}})
person Dan    schedule 29.01.2014

Дэн просто предлагает: в ваших маршрутах, если вы поместите правило ресурса, например:

post 'leagues/:id'/teams, to: 'leagues#teams', defaults: { format: 'json' }

вы можете пропустить «.json» в своем запросе

$http.post('/leagues/'+$scope.team.league_id+"/teams.json" => $http.post('/leagues/'+$scope.team.league_id+"/teams"

Но ваш контроллер должен отвечать объекту json.

person tenaz3.comp    schedule 10.07.2014