【问题标题】:Rails 4 and Angularjs serialization issueRails 4 和 Angularjs 序列化问题
【发布时间】:2014-01-29 01:50:47
【问题描述】:

当我尝试将 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() 时,对于 team_params 函数中的 permit 调用,我收到错误“undefined method `permit' for #”。在错误页面中,参数部分如下所示:

{"team"=>"{\"name\":\"\",\"league_id\":6,\"players\":[{\"name\":\"Dan\",\"email\":\"daniel.carpenter01@gmail.com\"}]}", "league_id"=>"6"}

有谁知道为什么我从 angular 传递的参数被解释为字符串?

【问题讨论】:

    标签: json angularjs serialization ruby-on-rails-4 controller


    【解决方案1】:

    我找到了答案。我从角度错误地制作了http帖子。下面是正常工作的 $http 代码。

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

    【讨论】:

      【解决方案2】:

      丹只是一个建议:如果你把资源规则放在你的路线中:

      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 对象。

      【讨论】:

        猜你喜欢
        • 2011-05-06
        • 2014-05-09
        • 2010-10-10
        • 2011-04-05
        • 2015-03-20
        • 2021-04-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多