我在新的rails项目中使用angularjs
和InheritedResources gem
。我想在这个项目中使用关联。我发现Singletons
与InheritedResources
有关联。我创建了2个模型并完成它们,如下所示:
districts_controller.rb
:
class DistrictsController < InheritedResources::Base
respond_to :json
def district_params
params.require(:district).permit(:name)
end
end
calculations_controller.rb
:
class CalculationsController < InheritedResources::Base
respond_to :json
singleton_belongs_to :district
def calculation_params
params.require(:calculation).permit(:district_id, :price)
end
end
我的model.js
代码中有一个angularjs
,用于创建网址并将数据发布到rails应用程序:
model.js
:
'use strict';
var app = angular.module('app');
app.factory('District', ['$resource', function($resource) {
return $resource('/districts/:id', {id: '@id'});
}]);
app.factory('Calculation', ['$resource', function($resource){
return $resource('/districts/:district_id/calculations/:id', {district_id: '@district_id', id: '@id'});
}]);
我设置config/routes/rb
如下:
resources :districts, :defaults => {format: :json} do
resources :calculations, :defaults => {format: :json}
end
和rake routes
:
district_calculations GET /districts/:district_id/calculations(.:format) calculations#index {:format=>:json}
POST /districts/:district_id/calculations(.:format) calculations#create {:format=>:json}
但是当我将数据从angularjs
发布到rails application
时,数据会被收到rails服务器,但是当rails服务器想要将数据保存到数据库时,我会收到以下错误:
Started POST "/districts/17/calculations" for 127.0.0.1 at 2014-08-10 12:56:53 +
0430
Processing by CalculationsController#create as JSON
Parameters: {"district_id"=>"17", "price"=>";sadkas", "calculation"=>{"distric
t_id"=>"17", "price"=>";sadkas"}}
Completed 500 Internal Server Error in 1ms
NoMethodError (undefined method `build' for #<Class:0x00000006371f30>)
如果我使用不带InheritedResorces
的rails控制器,我知道我必须使用build
方法而不是new
,但我不知道如何解决这个问题。有什么想法吗?!