POST 到 Rails API 使用 Rails 和 HTTParty

POST to a Rails API using Rails and HTTParty

如果这看起来是一个非常基本的问题,我很抱歉,但我也是这方面的新手,所以...我在使用 API 的应用程序中遇到基本操作问题(都在 rails 上), 但是现在我想做的就是通过应用程序的请求在 API 的数据库中创建一条记录。

这就是我到目前为止所做的:

对于 API,我遵循了本教程 railscasts.com: the rails api-gem,并通过 rails g scaffold City name:string description:string 命令制作了 City 模型。

生成的控制器是这样的:

class CitiesController < ApplicationController
  before_action :set_city, only: [:show, :update, :destroy]

  # GET /cities
  # GET /cities.json
  def index
    @cities = City.all

    render json: @cities
  end

  # GET /cities/1
  # GET /cities/1.json
  def show
    render json: @city
  end

  # POST /cities
  # POST /cities.json
  def create
    @city = City.new(city_params)

    if @city.save
      render json: @city, status: :created, location: @city
    else
      render json: @city.errors, status: :unprocessable_entity
    end
  end

  # PATCH/PUT /cities/1
  # PATCH/PUT /cities/1.json
  def update
    @city = City.find(params[:id])

    if @city.update(city_params)
      head :no_content
    else
      render json: @city.errors, status: :unprocessable_entity
    end
  end

  # DELETE /cities/1
  # DELETE /cities/1.json
  def destroy
    @city.destroy

    head :no_content
  end

  private

    def set_city
      @city = City.find(params[:id])
    end

    def city_params
      params.require(:city).permit(:name, :description)
    end
end

注意城市的路线是:

cities GET    /cities(.:format)     cities#index
       POST   /cities(.:format)     cities#create
  city GET    /cities/:id(.:format) cities#show
       PATCH  /cities/:id(.:format) cities#update
       PUT    /cities/:id(.:format) cities#update
       DELETE /cities/:id(.:format) cities#destroy

现在,在将使用 API 服务的应用程序中,我通过 rails g controller cities index new show edit destroy 命令创建了城市控制器,并放置了一些代码来尝试通过 API 创建记录, 但它什么也没做。

控制器代码为:

class CitiesController < ApplicationController
  before_filter :authenticate_user!

  def index
  end

  def new
    @result = HTTParty.post('url_of_my_api_on_heroku/cities', :body => {:name => 'New York', :description => 'ABC'}.to_json, :headers => { 'Content-Type' => 'application/json' })
  end

  def show
  end

  def edit
  end

  def destroy
  end
end

当我转到我的应用程序的新视图时(我'我这样做只是为了测试),但是当我在我的应用程序中转到城市的 new 视图时,部署在 Heroku 上的 API 总是 returns 一个空散列,它 return 城市的散列,所以,我不知道我在 API 上有什么问题,在使用 API 的应用程序上,或者在两者上,有人可以告诉我如何使这项工作?

在 CitiesController 中,我们需要 'city_params'

中的 :city
def city_params
  params.require(:city).permit(:name, :description)
end

但是在调用 api 时,我们错过了 :city

def new
  @result = HTTParty.post('url_of_my_api_on_heroku/cities', :body => {:name => 'New York', :description => 'ABC'}.to_json, :headers => { 'Content-Type' => 'application/json' })
end

所以,应该是:

def new
  @result = HTTParty.post('url_of_my_api_on_heroku/cities', :body => {:city => {:name => 'New York', :description => 'ABC'}}.to_json, :headers => { 'Content-Type' => 'application/json' })
end