【发布时间】: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