簡體   English   中英

Rails:使用Rails將HTTP發布到API並且HTTParty不起作用

[英]Rails: Post JSON to API Using Rails and HTTParty Not Working

我對Rails中的API很新,雖然我已經獲得了一些關於如何構建我的HTTParty Post Request的幫助,但是我發送的有效負載(數據)對我的API數據庫沒有影響

我想要的只是通過我的應用程序的POST請求在API的數據庫上創建一條記錄。

那就是每當我創建一本書時,在兩個數據庫(我的數據庫和通過我的應用程序的POST請求的API數據庫)上創建記錄。

對於將使用API​​的應用程序我使用HTTParty gem,但請求僅在不影響API數據庫的情況下運行

這是我的HTTParty郵政索取代碼

@result = HTTParty.post(' https://www.pingme.com/wp-json/wplms/v1/user/register',
    :body => {
                :books => {  
                  :name => '#{name}',
                  :author => '#{author}',
                  :description => '#{description}',
                  :category_id => '#{category_id}',
                  :sub_category_id => '#{sub_category_id}'}.to_json, 
    :headers => { 'Content-Type' => 'application/json', 'Authorization' => '77d22458349303990334xxxxxxxxxx' })

但這不會影響API的數據庫,而只影響我的Rails應用程序的數據庫

這是執行的日志代碼

Started POST "/books" for 127.0.0.1 at 2019-03-27 11:51:18 +0100
Processing by BooksController#create as HTML

Parameters: {"utf8"=>"✓", "authenticity_token"=>"xxxxxxxx", "book"=>{"name"=>"veb", "author"=>"vebturejjd", "description"=>"aisiosoijjdkdp", "category_id"=>"text books", "sub_category_id"=>"children"}, "commit"=>"Create Book"}
   (0.1ms)    begin transaction

↳ app/controllers/books_controller.rb:32
      Book Create (0.5ms)  INSERT INTO "books" ("name", "author", "description", "category_id", "sub_category_id", "created_at", "updated_at", "client_id") VALUES (?, ?, ?, ?, ?, ?, ?)  [["name", "vebturejjd"], ["author", "vebturejjd"], ["description", "aisiosoijjdkdp"], ["category_id", "text books"], ["sub_category_id", "children"], ["created_at", "2019-03-27 10:51:18.239045"], ["updated_at", "2019-03-27 10:51:18.239045"]]
      ↳ app/controllers/books_controller.rb:32
       (77.8ms)  commit transaction

我在終端中找不到@result的任何日志,仍然想知道它是否被跳過或者沒有在運行中運行,或者有更好的方法來執行它。

我需要一些關於如何解析ruby以便發布到API數據庫的幫助。

這是我的書籍控制器,用於創建書籍

require 'httparty'

class BooksController < ApplicationController
  include HTTParty

  before_action :set_book, only: [:show, :edit, :update, :destroy]
  before_action :authenticate_admin!, except: %i[show index]
  skip_before_action :verify_authenticity_token

  # GET /books
  # GET /books.json
  def index
    @books = Book.search(params[:keywords]).paginate(:page => params[:page], :per_page => 9).order('created_at DESC')
  end

  # GET /books/1
  # GET /books/1.json
  def show
  end

  # GET /books/new
  def new
    @book = Book.new
  end

  # GET /books/1/edit
  def edit
  end

  # POST /books
  # POST /books.json
  def create
    @book = Book.new(book_params)

    respond_to do |format|
      if @book.save
        format.html { redirect_to @book, notice: 'Book was successfully created.' }
        format.json { render :show, status: :created, location: @book }
      else
        format.html { render :new }
        format.json { render json: @book.errors, status: :unprocessable_entity }
      end
    end

    @result = HTTParty.post(' https://www.pingme.com/wp-json/wplms/v1/user/register',
    :body => {
                :books => {  
                  :name => '#{name}',
                  :author => '#{author}',
                  :description => '#{description}',
                  :category_id => '#{category_id}',
                  :sub_category_id => '#{sub_category_id}'}.to_json, 
    :headers => { 'Content-Type' => 'application/json', 'Authorization' => '77d22458349303990334xxxxxxxxxx' })

  end

  # PATCH/PUT /books/1
  # PATCH/PUT /books/1.json
  def update
    respond_to do |format|
      if @book.update(book_params)
        format.html { redirect_to @book, notice: 'Book was successfully updated.' }
        format.json { render :show, status: :ok, location: @book }
      else
        format.html { render :edit }
        format.json { render json: @book.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /books/1
  # DELETE /books/1.json
  def destroy
    @book.destroy
    respond_to do |format|
      format.html { redirect_to books_url, notice: 'Book was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_book
      @book = Book.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def book_params
      params.require(:book).permit(:name, :author, :description, :category_id, :sub_category_id)
    end
end

請高度贊賞任何形式的協助。 謝謝。

永遠不會在控制器中調用@result ,因為重定向在執行到達之前發生。

我會在一個方法中包裝HTTP調用,而不是將它分配給一個實例變量,因為它正在處理事情,而不是分配它們然后將它帶到format.html {}塊中。 像這樣的東西:

def create
  @book = Book.new(book_params)

  respond_to do |format|
    if @book.save
      format.html {
        post_to_api 
        redirect_to @book, notice: 'Book was successfully created.' 
      }
      format.json { render :show, status: :created, location: @book }
    else
      format.html { render :new }
      format.json { render json: @book.errors, status: :unprocessable_entity }
    end
  end
end

private

def post_to_api
  HTTParty.post(' https://www.pingme.com/wp-json/wplms/v1/user/register',
    :body => {
              :books => {  
                :name => "#{@book.name}",
                :author => "#{@book.author}",
                :description => "#{@book.description}",
                :category_id => "#{@book.category_id}",
                :sub_category_id => "#{@book.sub_category_id}"}.to_json, 
    :headers => { 
              'Content-Type' => 'application/json',
              'Authorization' => '77d22458349303990334xxxxxxxxxx'
    }
  )
end

在@ vincent-rolea和@oneWorkingHeadphone的貢獻之后,我找到了一個解決這個問題的工作方案。

以下是修正后的HTTParty Post Request。

@results = HTTParty.post(' https://www.pingme.com/wp-json/wplms/v1/user/register',
      :body => {    
                :name => "#{@book.name}",
                :author => "#{@book.author}",
                :description => "#{@book.description}",
                :category_id => "#{@book.category_id}",
                :sub_category_id => "#{@book.sub_category_id}"}.to_json, 
      :headers => { 
                   'Content-Type' => 'application/json',
                   'Authorization' => '77d22458349303990334xxxxxxxxxx'
      }
)

確保執行以下操作以使其正常工作

  1. 在應用程序中安裝並配置HTTParty gem
  2. 在您希望執行請求的控制器中包含並要求HTTParty gem
  3. HTTParty gem post請求傳遞給該控制器中的實例變量

這是我的控制器中的HTTParty Post Request的實現

require 'httparty'

class BooksController < ApplicationController
  include HTTParty

  before_action :set_book, only: [:show, :edit, :update, :destroy]
  before_action :authenticate_admin!, except: %i[show index]
  skip_before_action :verify_authenticity_token

  # GET /books
  # GET /books.json
  def index
    @books = Book.search(params[:keywords]).paginate(:page => params[:page], :per_page => 9).order('created_at DESC')
  end

  # GET /books/1
  # GET /books/1.json
  def show
  end

  # GET /books/new
  def new
    @book = Book.new
  end

  # GET /books/1/edit
  def edit
  end

  # POST /books
  # POST /books.json
  def create
    @book = Book.new(book_params)

    respond_to do |format|
      if @book.save
        format.html { redirect_to @book, notice: 'Book was successfully created.' }
        format.json { render :show, status: :created, location: @book }
      else
        format.html { render :new }
        format.json { render json: @book.errors, status: :unprocessable_entity }
      end
    end

    @results = HTTParty.post(' https://www.pingme.com/wp-json/wplms/v1/user/register',
          :body => {    
                    :name => "#{@book.name}",
                    :author => "#{@book.author}",
                    :description => "#{@book.description}",
                    :category_id => "#{@book.category_id}",
                    :sub_category_id => "#{@book.sub_category_id}"}.to_json, 
          :headers => { 
                       'Content-Type' => 'application/json',
                       'Authorization' => '77d22458349303990334xxxxxxxxxx'
          }
    )
  end

  # PATCH/PUT /books/1
  # PATCH/PUT /books/1.json
  def update
    respond_to do |format|
      if @book.update(book_params)
        format.html { redirect_to @book, notice: 'Book was successfully updated.' }
        format.json { render :show, status: :ok, location: @book }
      else
        format.html { render :edit }
        format.json { render json: @book.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /books/1
  # DELETE /books/1.json
  def destroy
    @book.destroy
    respond_to do |format|
      format.html { redirect_to books_url, notice: 'Book was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_book
      @book = Book.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def book_params
      params.require(:book).permit(:name, :author, :description, :category_id, :sub_category_id)
    end
end

就這樣

我希望這有幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM