I use angularjs
and InheritedResources gem
in my new rails project. I want use association in this project. I find Singletons
for association with InheritedResources
. I create 2 model and complete them like below:
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
and have a model.js
in my angularjs
code that create url and post data to rails application:
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'});
}]);
I set config/routes/rb
like below:
resources :districts, :defaults => {format: :json} do
resources :calculations, :defaults => {format: :json}
end
and rake routes
:
district_calculations GET /districts/:district_id/calculations(.:format) calculations#index {:format=>:json}
POST /districts/:district_id/calculations(.:format) calculations#create {:format=>:json}
But when I post data from angularjs
to rails application
, data are recieved to rails server, but when rails server want to save data to database, I get below error:
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>)
If I used rails controller without InheritedResorces
, I know I have to use build
method instead of new
, but I don't know how can I fix this problem. Any idea?!