NoMethodError用于"计算"使用has_one时(与has_many一起使用)

时间:2014-08-10 07:08:28

标签: ruby-on-rails ruby-on-rails-4

我在新的rails项目中使用InheritedResources。我有2个型号:districtcalculation。我想使用rails关联,为此,当我使用has_many时,所有事情都是正确的,但当我使用has_one时,我得到以下错误:

Started GET "/districts/17/calculations" for 127.0.0.1 at 2014-08-10 11:29:07 +0
430
Processing by CalculationsController#index as JSON
  Parameters: {"district_id"=>"17"}
  District Load (0.0ms)  SELECT  "districts".* FROM "districts"  WHERE "district
s"."id" = ? LIMIT 1  [["id", 17]]
Completed 500 Internal Server Error in 8ms

NoMethodError (undefined method `calculations' for #<District:0x0000000545d968>)

districts_controller.rb

class DistrictsController < InheritedResources::Base
  respond_to :json

  def district_params
    params.require(:district).permit(:name)
  end
end

district.rb

class District < ActiveRecord::Base
  has_one :calculation, :dependent => :destroy
end

calculations_controller.rb

class CalculationsController < InheritedResources::Base

  belongs_to :district
  respond_to :json

  def calculation_params
    params.require(:calculation).permit(:district_id, :price)
  end

end

calculation.rb

class Calculation < ActiveRecord::Base
  belongs_to :district
end

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}
 new_district_calculation GET    /districts/:district_id/calculations/new(.:format)      calculations#new {:format=>:json}

当我使用has_many关联并正常工作时,问题已解决,但当我使用has_one时,我收到此错误。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

将您的方法更改为district.calculation,而不是district.calculations

当您使用has_many计算时,事情会起作用,因为district.calculations会调用引用该区域的所有(一个或多个)计算。 Rails期望对has_many关联进行复数形式的计算。

当您将关联更改为has_one时,这会中断,因为当区域has_one计算时,您永远不能引用多个计算。 Rails足够聪明,可以知道这一点,并且需要使用单数.calculation方法进行has_one关联。