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.
――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
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.
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/
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
We will create each table. As mentioned above, this time we will create User, Book, Review tables.
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
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
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.
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.
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"
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.
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