为什么我的模型没有在Rails API中更新?

时间:2019-04-26 22:23:57

标签: ruby-on-rails rest api

我正在Rails中开发API,并通过另一个Rails应用程序与之交互。到目前为止,一切都可以正常工作,使用POST和GET对用户进行身份验证,创建记录和检索数据。但是,现在我无法让PUT操作更新记录。看来它正确地调用了API,并且API返回了200响应,但查看日志似乎并不像Rails在执行UPDATE语句。最奇怪的是没有错误或警告。

这是日志。 (数据是伪造的数据,因此我不必费心编辑它)

Started PUT "/affiliates/17" for ::1 at 2019-04-26 17:42:51 -0400
Processing by AffiliatesController#update as HTML
  Parameters: {"id"=>"17", "username"=>"teracole", "email"=>"dan@purdy.io", "first_name"=>"Max", "last_name"=>"Max", "company"=>"Dach LLC", "manager_id"=>"3"}
  [1m[36mUser Load (0.3ms)[0m  [1m[34mSELECT  "users".* FROM "users" WHERE "users"."id" = $1 LIMIT $2[0m  [["id", 2], ["LIMIT", 1]]
  ↳ app/controllers/application_controller.rb:12
  [1m[36mAffiliate Load (0.2ms)[0m  [1m[34mSELECT  "affiliates".* FROM "affiliates" WHERE "affiliates"."id" = $1 LIMIT $2[0m  [["id", 17], ["LIMIT", 1]]
  ↳ app/controllers/affiliates_controller.rb:50
  [1m[35m (0.1ms)[0m  [1m[35mBEGIN[0m
  ↳ app/controllers/affiliates_controller.rb:31
  [1m[36mAffiliate Exists (0.3ms)[0m  [1m[34mSELECT  1 AS one FROM "affiliates" WHERE "affiliates"."username" = $1 AND "affiliates"."id" != $2 LIMIT $3[0m  [["username", "tera.cole"], ["id", 17], ["LIMIT", 1]]
  ↳ app/controllers/affiliates_controller.rb:31
  [1m[35m (0.1ms)[0m  [1m[35mCOMMIT[0m
  ↳ app/controllers/affiliates_controller.rb:31
Completed 200 OK in 8ms (Views: 0.9ms | ActiveRecord: 1.0ms)

您可以在日志中看到参数数据。控制器动作非常简单:

# PATCH/PUT /affiliates/1
  def update
    if @affiliate.update(affiliate_params)
      render json: @affiliate
    else
      render json: @affiliate.errors, status: :unprocessable_entity
    end
  end

在此先感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

事实证明,无论出于何种原因,put方法都要求我在标头中标识内容类型。 Post并没有这样做,但是在我的HttParty调用中更改了行即可解决此问题:

false