【问题标题】:Testing create resource with curl return status code 500使用 curl 返回状态码 500 测试创建资源
【发布时间】:2012-11-09 02:15:10
【问题描述】:

我正在使用 curl 手动测试 Rails 3 的 Api 创建操作,但我不断收到 Internal server error(500)。我有一个产品模型,这是我的控制器中的创建操作和我尝试过的命令....

#command
curl -i -H "Accept: application/json"  -X POST -d "product[product_name]=dvd"  http://localhost:3000/api/products  

#controller
module Api  
  class ProductsController < ApplicationController
    respond_to :json

     def create
       @product = Product.new(params[:product])
       respond_to do |format|
         if @product.save
           format.html { redirect_to @product, notice: 'Product was successfully created.' }
           format.json { render json: @product, status: :created, location: @product }
         else
           format.html { render action: "new" }
           format.json { render json: @product.errors, status: :unprocessable_entity }
         end
       end
     end
   end
 end

我在这里缺少什么?提前谢谢你。

【问题讨论】:

  • 您可以在服务器日志中看到错误消息。 `
  • 在日志中说WARNING: Can't verify CSRF token authenticity Completed 500 Internal Server Error in 0ms ActiveModel::MassAssignmentSecurity::Error (Can't mass-assign protected attributes: product_name): app/controllers/api/products_controller.rb:72:in new' app/controllers/api/products_controller.rb:72:in create'

标签: ruby-on-rails ruby-on-rails-3 rest curl


【解决方案1】:

根据 MassAssignmentSecurity 错误,您似乎只需让您的模型上的 product_name 字段可访问:

class Product < ActiveRecord::Base
  attr_accessible :product_name
  #... other code...
end

【讨论】:

  • ` (0.1ms) 开始事务 SQL (0.5ms) INSERT INTO "products" ("category_id", "created_at", "details", "product_name", "publisher_id", "updated_at")值 (?, ?, ?, ?, ?, ?) [["category_id", nil], ["created_at", Wed, 21 Nov 2012 16:21:30 UTC +00:00], ["details", nil], ["product_name", "dvd"], ["publisher_id", nil], ["updated_at", Wed, 21 Nov 2012 16:21:30 UTC +00:00]] (5.9ms) 提交事务完成500 Internal Server Error in 10ms NoMethodError (undefined method api_v1_products_controller_product_url' for #&lt;Api::V1::ProductsController:0x007f94a3a81788&gt;):
  • 我收到上面的错误,好像是在尝试插入然后失败。
  • 看起来插入工作正常,但它正在尝试基于当前控制器构建 URL。使用 respond_with 可能会更好。签出此API tutorial
  • 这是另一个可能有用的链接asciicasts.com/episodes/224-controllers-in-rails-3
  • 非常感谢,现在一切都很好。
猜你喜欢
  • 2015-08-14
  • 1970-01-01
  • 2018-06-26
  • 2017-03-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-30
  • 1970-01-01
相关资源
最近更新 更多