ActiveRecord::AssociationTypeMismatch:应为User(#49785948),得到的是



我有一个Grape api,我想保存嵌套的数据。

我有一个这样的模型:

class Vehicule < ActiveRecord::Base
  before_validation :set_principal, :if =>:new_record?
  belongs_to :user
  accepts_nested_attributes_for :user
end

葡萄api:

# app/controller/api/v1/vehicules.rb
resource :vehicules do
  desc "Update a vehicule."
    params do
      optional :confort, type: Float, desc: ""
      optional :user, type: Hash do
        optional :name, type: String
      end
  end
  put ':id' do
    #authenticate! @todo
    Vehicule.find(params[:id]).update(vehicule_params)
  end

这是我的测试文件

test "PUT /api/v1/vehicules/1" do
  put("/api/v1/vehicules/1", { 'confort' => 3.4, 'user' => {'name' => 'name changed'} }, :format => "json")
  assert(200, last_response.status)
  vehicule = Vehicule.find(1)
  assert_equal('name changed', vehicule.user.name, "Le nom de l'utilisateur aurait dû changer")
end

消息是

  1) Error: API::V1::VehiculesTest#test_PUT_/api/v1/vehicules/1: ActiveRecord::AssociationTypeMismatch: User(#49785948) expected, got Hashie::Mas h(#52717320)
    app/controllers/api/v1/vehicules.rb:38:in `block (2 levels) in <class:Vehicu les>'
    test/controllers/api/v1/vehicules_test.rb:18:in `block in <class:VehiculesTe st>'

我做错了什么?是我发送数据的方式,还是我的结构/声明?

您必须使用'user_attributes'关键字才能使用嵌套属性。所以你必须这样更改你的参数块:

  params do
    optional :confort, type: Float, desc: ""
    optional :user_attributes, type: Hash do
      optional :name, type: String
    end
  end

测试文件必须相应地更改。

最新更新