1

我在我的新 Rails 项目中使用angularjsand 。InheritedResources gem我想在这个项目中使用关联。我发现SingletonsInheritedResources. 我创建了 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代码中创建 url 并将数据发布到 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}

但是当我从angularjsto发布数据时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>)

如果我在没有 的情况下使用 rails 控制器InheritedResorces,我知道我必须使用build方法而不是new,但我不知道如何解决这个问题。任何想法?!

4

0 回答 0