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

时间:2019-03-26 17:29:21

标签: ruby-on-rails json api httparty

我对Rails中的API还是很陌生,因此对于我所面临的问题,我将需要一些帮助。

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

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

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

对于将使用该API的应用程序,我正在使用HTTParty gem

我尝试使用以下代码在“图书控制器”的创建操作中实现:

 @result = HTTParty.post(' https://www.pingme.com/wp-json/wplms/v1/user/register', 
          :body => {  :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' })

这是我的用于创建图书的图书控制器

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 => {  :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

但是当我创建书籍时,它仍然不会通过发布请求在API数据库上创建这些书籍。

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

2 个答案:

答案 0 :(得分:1)

在执行请求时检查您的日志,但我怀疑您需要将身体更改为:

{
  :book => {  
    :name => '#{name}',
    :author => '#{author}',
    :description => '#{description}',
    :category_id => '#{category_id}',
    :sub_category_id => '#{sub_category_id}'
  }
}.to_json

请注意,顶部的book键是不同的。

答案 1 :(得分:0)

在@ paulo-fidalgo和@tejasbubane的贡献之后,我找到了解决该问题的有效方法。

这是更正后的HTTParty发布请求

const aMonthAgo = moment().subtract(30, 'days').toDate();