Rails:使用Rails和HTTParty无法将JSON发布到API

时间:2019-03-27 12:22:38

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

尽管我已经获得了一些有关如何构造HTTParty Post Request的帮助,但是我对Rails中的API还是很陌生,但是我发送的有效负载(数据)不会影响我的API数据库

我想要的是通过来自我的应用程序的POST请求在API的数据库上创建一条记录。

每当我创建一本书时,即在两个数据库(我的数据库和API的数据库中,通过来自我的应用程序的POST请求)上创建一条记录。

对于将使用该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的日志,仍然想知道它是被跳过还是没有在运行时运行,或者有更好的方法。

关于如何解析红宝石以发布到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

请提供任何形式的帮助,我们将不胜感激。谢谢。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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发布请求传递到该控制器中的实例变量

这是我的控制器中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

我希望这会有所帮助。

在有帮助的情况下将此答案赞为有用,或在答案下方评论以进一步说明。