POST to a Rails API using Rails and HTTParty
很抱歉,这似乎是一个非常基本的问题,但是我在这个问题上还是个新手,所以...我在使用API??的应用程序中遇到基本操作方面的问题(都在轨道上),但是让我们说现在我要做的就是通过应用程序的请求在API的数据库中创建一条记录。
所以这是我到目前为止所做的:
- 对于API,我使用了rails-api gem。
- 对于使用API??的应用程序,我使用了HTTParty gem。
对于API,我遵循了本教程railscasts.com:rails api-gem,并通过
结果控制器是这样的:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 | 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 |
请注意,城市的路线是:
1 2 3 4 5 6 | 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??服务的应用程序中,我使城市控制器通过
控制器的代码为:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | 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 York"(纽约),描述为" ABC")(我只是为了测试)但是当我进入应用程序中的城市的
在CitiesController中,我们要求'city_params'中的:city
1 2 3 | def city_params params.require(:city).permit(:name, :description) end |
但是当调用api时,我们错过了:city
1 2 3 | 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 |
因此,应为:
1 2 3 | 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 |