2014-01-29 30 views
0

我在嘗試向rails控制器中的create action發送json對象時遇到問題。我的params中的變量被解釋爲字符串而不是json對象。這是我的代碼。Rails 4和Angularjs序列化問題

角控制器

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()我得到的錯誤「未定義的方法'許可證」爲#」在team_params功能允許呼入。在錯誤頁面的參數部分看起來是這樣的:

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

有誰知道爲什麼我的PARAMS從角傳遞被解釋爲一個字符串?

回答

0

我找到了答案。我正在從角度錯誤地製作http帖子。以下是正常工作的$ http代碼。

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

丹只是一個建議:在你的路由,如果你把資源類的規則:

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

您可以在您的要求

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

但跳過 '以.json' 你控制器必須響應json對象。