2014-01-29 31 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对象。