Rails:使用Rails将HTTP发布到API并且HTTParty不起作用

问题描述 投票:0回答:2

我对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

请高度赞赏任何形式的协助。谢谢。

ruby-on-rails json ruby api httparty
2个回答
0
投票

从未在控制器中调用@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

0
投票

在@ 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

就这样

我希望这有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.