0
我正在尝试使用Angular和Rails将输入保存到我的数据库中。在当执行的动作,我收到了400 (Bad Request)
错误控制台日志和Rails错误是如下的那一刻,保存数据给出错误,param丢失或者数值为空
Started POST "/movies.json" for 127.0.0.1 at 2015-08-24 07:57:09 +0200
Processing by MoviesController#create as JSON
Parameters: {"titles"=>"Star", "movie"=>{}}
User Load (0.1ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT 1 [["id", 1]]
Completed 400 Bad Request in 12ms (ActiveRecord: 0.2ms)
ActionController::ParameterMissing (param is missing or the value is empty: title):
app/controllers/movies_controller.rb:24:in `movie_params'
app/controllers/movies_controller.rb:8:in `create'
的routes.rb
resources :movies, only: [:create, :index, :show] do
end
使用的search.html.haml模板,这里用户应该输入标题。
#addMovie{"ng-controller" => "addMovieCtrl"}
%div{"ng-click" => "addMovie()"}
%input{:type => "text", "ng-model" => "title"}
addMovie action.
我movieController.js,这是操作时,将触发对DIV用户点击在#addMovie
angular.module('addMovieseat', ['ui.router', 'templates'])
.controller('addMovieCtrl', ['$scope', 'movies',
function($scope, movies){
$scope.movies = movies.movies;
$scope.addMovie = function(){
if(!$scope.title || $scope.title === '') { return; }
movies.create({
titles: $scope.title,
});
$scope.title = '';
};
}
])
角服务,
angular.module('addMovieseat')
.factory('movies', ['$http', function($http){
var o = {
movies: []
};
o.create = function(movie){
return $http.post('/movies.json', movie).success(function(data){
o.movies.push(data);
});
};
return o;
}])
而且movies_controller。 rb
class MoviesController < ApplicationController
def index
respond_with Movie.all
end
def create
respond_with Movie.create(movie_params)
end
private
def movie_params
params.require(:movie).permit(:title)
end
end
改变'titles'到'title'确实固定的'400错误'。当我执行保存操作并查看movies.json文件时,它说'[null,null,null,null]'所以标题没有被保存吗?只需输入空白?我在哪里改变你建议的参数? –
hmm ..打开'rail console'并键入'Movie.last'。如果你看到那里看起来正确的东西,那么它正确保存。如果您看到类似于'ActiveRecord Association []'或具有'title:nil'的电影记录的东西,那么它不能正确保存。如果正确保存,那么json输出存在问题。 – thedanotto
你说得对,标题正确保存。所以JSON输出存在问题。去看看它。谢谢。 –