使用Rails和HTTParty

时间:2015-11-15 00:26:25

标签: ruby-on-rails api httparty rails-api

我很抱歉,如果这似乎是一个非常基本的问题,但我也很新,所以......我在使用API​​的应用程序中的基本操作有问题(两者都在轨道上), 但是让我们说现在我想做的就是通过应用程序的请求在API的数据库中创建一条记录。

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

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

生成的控制器是:

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

我要做的是创建一个城市记录(名称为'纽约',描述为“ABC”)当我转到我的应用程序的新视图时(我正在这样做以测试但是当我在我的应用程序中转到城市的new视图时,部署在Heroku上的API总是返回一个空哈希,它返回城市的哈希,所以,我不知道我是否有东西在API上,在使用API​​的应用程序上,或者在这两者中,有人可以告诉我如何使其工作?

1 个答案:

答案 0 :(得分:1)

在CitiesController中,我们要求:城市&#39; city_params&#39;

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

但是当打电话给api时,我们错过了传球:城市

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