Rails: def create 不使用 Rest 添加数据到 table

Rails: def create does not add data to table using Rest

我想通过 rest api 和 url 添加数据到 table: 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 index 会被触发,但是当我这样做时: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)

而我的 table 是空的。有2个问题:

  1. 我不明白为什么 index 仍然被触发,我怎样才能让 def create 通过 rest api 在杂货栏中实际插入值。

    • [已解决] 我使用了一个名为 Postman 的客户端来解决这个问题,但仍然面临问题 (2),因为所有空值都输入了我的 table 而不是通过 url。我的命令行日志现在显示 [logs]
  2. 一旦它被触发,那么我的代码是否适合 "create" def?

    • [已解决] 问题出在我通过 post 发送值的方式上。我必须将值添加到 Postman 中的表单数据选项卡 (key,val) 而不是通过 url 才能工作

[日志]

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)

创建操作需要 POST 请求,当您在浏览器中访问 localhost:3000/api/v1/shoppinglist#create?grocery=fruits 时,它发送 GET 请求而不是 POST 请求,将其视为 URI 并因此触发索引操作。 要发送 POST 请求,您可以使用 CURL command in terminal or httparty

curl -H 'Content-Type: application/json'-H 'Accept: application/json' -X POST http://localhost:3000/api/v1/shoppinglists -d {"grocery": "fruits"}

其中-H指的是请求中设置的headers,-X用于更改默认GET动词,-d用于您要发送的数据. 详情参考curl