[RUBY] How to store Rakuten API data in a table

Introduction

If you are developing a web application in a portfolio etc., you may want to use an external API.

With regard to the Rakuten API introduced this time, acquiring data itself is not so difficult. If you get the app ID and install the gem, you can get the data relatively easily.

However, if you try to utilize the acquired data in the app, such as "Store API data in a table and associate it with other tables ...", the difficulty will increase a little (I personally think, lol).

In this article, we will describe "How to store the acquired data in the table" and "Association settings". Also, at the end, I provided a search function in the app and briefly described the code to display the necessary data.

I hope it will be helpful for those who want to use Rakuten API from now on.

Note

――This article refers to Rakuten API. There are various Rakuten APIs, but this time we will use the Rakuten Books Book Search API.

--In this article, we will omit the part of API data acquisition (application ID acquisition and gem installation). For the data acquisition part, please refer to the following article.   https://freesworder.net/rakuten-api-rails/ https://qiita.com/hakusai_it/items/6453c4577647cb8995d3

environment

ER diagram

This time, we will proceed with the discussion with the following ER diagram. The Book table is the table that stores the data. We have set up a Review table to write reviews about the books we have acquired.

ER図.png

Let's take a look at the columns in the Book table. This time, the primary_key of the Book table will use "isbn", which is a unique number of the product, instead of "id". "Title" and "author" are the title and author name of the book, respectively. "Item_caption" is the product description, "item_url" is the url of Rakuten's product, and "middleimage_url" is the image of the book. There are various other data, so if you are interested, please refer to the following URL. https://webservice.rakuten.co.jp/api/booksbooksearch/

Mounting process

Overview

We will implement it in the following flow.

step1. Creating a table step2. Association settings step3. Routing settings step4. Controller settings step5. Creating a search page

"Association settings" are step1 and step2, "Store the acquired data in a table" is step3, step4, "Implementation of search page" will be implemented in step5

step1. Creating a table

We will create each table. As mentioned above, this time we will create User, Book, Review tables.

User table creation

The User table hasn't changed. Let's create a model and perform the migration!

python


$ rails g model User name:string email:string password_digest:string
$ rails g db:migrate

Book table creation

First, we will create a model.

python


$ rails g model Book title:string author:string isbn:bigint url:string image_url:string

Next, we will rewrite the migration file. Since the primary_key of the Book table uses "isbn", which is the unique number of the product, instead of "id", it is necessary to rewrite the file.

The US mark of the file name is the Migration ID (the number on which the date etc. is written). I think the ActiveRecord :: Migration [6.0] part varies from person to person.

Add null: false, primary_key: true to the isbn part.

**************_create_books.rb


class CreateBooks < ActiveRecord::Migration[6.0]
  def change
    create_table :books, id: false do |t|
      t.string :title
      t.string :author
      t.bigint :isbn, null: false, primary_key: true
      t.string :url
      t.string :image_url

      t.timestamps
    end
  end
end

After rewriting the migration file, it will be migrated.

python


$ rails g db:migrate

Review table creation

Finally, we will create a Review table.

python


$ rails g model Review content:string user:references book:references

Next, we will rewrite the migration file. The US mark of the file name is the Migration ID (the number on which the date etc. is written). I think the ActiveRecord :: Migration [6.0] part varies from person to person.

**************_create_reviews.rb


class CreateReviews < ActiveRecord::Migration[6.0]
  def change
    create_table :books, id: false do |t|
      #foreign mentioned in the book part_key:Delete true
      t.references :book, null: false
      t.references :user, null: false, foreign_key: true

      t.timestamps
    end
    #The following code is newly added in this part
    add_foreign_key :bookcases, :books, column: :book_id , primary_key: :isbn
  end
end

After rewriting the migration file, we will execute the migration.

python


$ rails g db:migrate

This completes the table creation. Next is the association settings.

step2. Association settings

Set the association of each model.rb. Again, write the code so that the primary_key of the Book table is "isbn".

user.rb


class User < ApplicationRecord
  has_many :reviews, dependent: :destroy
end

book.rb


class Book < ApplicationRecord
  self.primary_key = "isbn"
  has_many :reviews, dependent: :destroy
end

review.rb


class Bookcase < ApplicationRecord
  belongs_to :user
  belongs_to :book, primary_key: "isbn"
end

Up to step2, table creation and association settings are complete. Since step3 and after, we will mainly explain how to store data in the Book table, so we will omit the User and Review models and describe only the Book model.

step3. Routing settings

This time, we have provided a search field and a/search action to display the search results. If necessary, set additional actions yourself.

routes.rb


get 'books/search', to: "books#search"

step4. Controller settings

First, create a controller file.

python


$ rails g controller books

Write the following code in the created controller file.

books_controller.rb


class BooksController < ApplicationController

  def search
    #Make an empty array here
    @books = []
    @title = params[:title]
    if @title.present?
      #In this part, the data (json data) obtained from Rakuten API is stored in results.
      #This time, we search the title of the book and set it to store the matching data.
      results = RakutenWebService::Books::Book.search({
        title: @title,
      })
      #In this part "@We will store the JSON data obtained from the API in "books".
      #read(result)Is set as a private method.
      results.each do |result|
        book = Book.new(read(result))
        @books << book
      end
    end
    #「@Each data in "books" will be saved.
    #Books that have already been saved have an unless syntax to exclude them.
    @books.each do |book|
      unless Book.all.include?(book)
        book.save
      end
    end
  end

  private
  #We will set the method of "narrowing down the necessary data from the data of Rakuten API" and "storing the data in the corresponding column".
  def read(result)
    title = result["title"]
    author = result["author"]
    url = result["itemUrl"]
    isbn = result["isbn"]
    image_url = result["mediumImageUrl"].gsub('?_ex=120x120', '')
    book_genre_id = result["booksGenreId"]
    item_caption = result["itemCaption"]
    {
      title: title,
      author: author,
      url: url,
      isbn: isbn,
      image_url: image_url,
      book_genre_id: book_genre_id,
      item_caption: item_caption
    }
  end
end

By step4, data storage in the table is complete. In step5, we will create a search page and a result output page.

step5. Creating a search page

Create a file called search.html.erb and write the code.

java:search.html.erb


#Show search bar
<%= form_tag(books_search_path, method: :get) do %>
  <%= text_field_tag :title, @title %>
  <%= button_tag type: "submit" %>
<% end %>

#Display search results
<% if @books %>
  <% @books.each do |book| %>
  #Please enter the data you want to display.
  #The code below displays the image, title, author name, and product description.
    <%= image_tag book.image_url %>
    <%= book.title %>
    <%= book.author %>
    <%= book.item_caption %>    
  <% end %>
<% end %>

This is the end of the mounting process. If you have any questions or mistakes, please let us know in the comments.

Recommended Posts

How to store Rakuten API data in a table
How to clear all data in a particular table
How to store data simultaneously in a model associated with a nested form (Rails 6.0.0)
How to make a unique combination of data in the rails intermediate table
How to add columns to a table
How to store a string from ArrayList to String in Java (Personal)
How to get date data in Ruby
How to insert a video in Rails
How to implement a job that uses Java API in JobScheduler
How to store the information entered in textarea in a variable in the method
[RubyOnRails] How to implement pull-down in form_with based on table data
How to publish a library in jCenter
How to overwrite Firebase data in Swift
How to display a web page in Java
How to run a djUnit task in Ant
How to add a classpath in Spring Boot
How to create a theme in Liferay 7 / DXP
How to implement a like feature in Rails
How to easily create a pull-down in Rails
(Ruby on Rails6) Creating data in a table
How to implement optimistic locking in REST API
How to make a follow function in Rails
How to automatically generate a constructor in Eclipse
How to fix a crash when deleting Realm data in Swift UI List
How to create a Java environment in just 3 seconds
How to implement a like feature in Ajax in Rails
How to launch another command in a Ruby program
How to display a browser preview in VS Code
[How to insert a video in haml with Rails]
How to write a date comparison search in Rails
How to mock a super method call in PowerMock
How to convert A to a and a to A using AND and OR in Java
How to convert a file to a byte array in Java
[Rails 6] How to set a background image in Rails [CSS]
[Rails] How to load JavaScript in a specific view
How to write a core mod in Minecraft Forge 1.15.2
[Ruby/Rails] How to generate a password in a regular expression
How to use Chain API
How to leave a comment
How to insert a video
How to create a method
How to use JSON data in WebSocket communication (Java, JavaScript)
How to change a string in an array to a number in Ruby
How to create a placeholder part to use in the IN clause
How to call and use API in Java (Spring Boot)
Create API to send and receive Json data in Spring
How to select a specified date by code in FSCalendar
How to display a graph in Ruby on Rails (LazyHighChart)
How to add the same Indexes in a nested array
Mapping to a class with a value object in How to MyBatis
How to develop and register a Sota app in Java
How to simulate uploading a post-object form to OSS in Java
How to join a table without using DBFlute and sql
How to create a service builder portlet in Liferay 7 / DXP
How to set up a proxy with authentication in Feign
How to get the latest live stream ID for a channel without using the YouTube Data API
How to find May'n in XPath
How to hide scrollbars in WebView
How to run JUnit in Eclipse
How to create a registration / update function where the table crosses
How to use Spring Data JDBC