我想通过rest api使用url:localhost:3000/api/v1/shoppinglists#create?grocery=fruits
我已经创建了一个模型,我的控制器位于api/v1/shoppinglists_controller.rb
下面,代码是:
shoppinglists_controller.rb:
module Api
module V1
class ShoppinglistsController < ApplicationController
def index
shop = Shoppinglist.all
render json: shop.to_json
end
def create
@tst = Shoppinglist.create(grocery: params[:grocery])
end
end
end
end
routes.rb中:
Rails.application.routes.draw do
namespace :api do
namespace :v1 do
get '/shoppinglists' => 'shoppinglists#index'
post '/shoppinglists' => 'shoppinglists#create'
end
end
end
模型迁移:shoppinglist.rb:
class CreateShoppinglists < ActiveRecord::Migration
def change
create_table :shoppinglists do |t|
t.integer :shopid
t.string :type
t.string :grocery
t.string :status
t.timestamps null: false
end
end
end
默认情况下,def索引会被触发但是当我执行:localhost:3000/api/v1/shoppinglist#create?grocery=fruits
然后我检查命令行时,我仍然看到:
Started GET "/api/v1/shoppinglists" for ::1 at 2015-06-23 23:59:06 -0400
Processing by Api::V1::ShoppinglistsController#index as HTML
Shoppinglist Load (0.3ms) SELECT "shoppinglists".* FROM "shoppinglists"
Completed 200 OK in 44ms (Views: 0.2ms | ActiveRecord: 0.4ms)
我的桌子是空的。有两个问题:
我不明白为什么仍然会index
被触发,如何让def create
通过rest api在杂货专栏中实际插入值。
Postman
的客户端来解决这个问题,但仍面临问题(2),因为所有空值都输入到我的表中,而不是通过url输入的值。我的命令行日志现在说[logs] 一旦它被触发,那么我的代码就是#34;创建&#34; DEF?
[日志]
Started POST "/api/v1/shoppinglists" for ::1 at 2015-06-24 01:03:44 -0400
Processing by Api::V1::ShoppinglistsController#create as */*
Can't verify CSRF token authenticity
(0.2ms) begin transaction
SQL (0.3ms) INSERT INTO "shoppinglists" ("created_at", "updated_at") VALUES (?, ?) [["created_at", "2015-06-24 05:03:44.714945"], ["updated_at", "2015-06-24 05:03:44.714945"]]
(8.2ms) commit transaction
Completed 200 OK in 12ms (ActiveRecord: 8.7ms)
答案 0 :(得分:1)
创建操作需要POST请求,当您在浏览器中访问localhost:3000 / api / v1 / shoppinglist#create?grocery = fruits时,会发送GET请求而不是POST请求,它作为URI并因此触发索引操作。 要发送POST请求,您可以在终端中使用CURL
命令或httparty
curl -H 'Content-Type: application/json'-H 'Accept: application/json' -X POST http://localhost:3000/api/v1/shoppinglists -d {"grocery": "fruits"}
其中 -H表示请求中设置的标头,-X表示更改默认GET谓词,-d表示要发送的数据。 For详情请参阅curl