This time I will post about how to display the information stored in the database in the view. In addition, I will post as if the information is already saved in the database.
The implementation flow is as follows.
① Description of controller action (show action) ② When the information you want to display is a character string ③ When the information you want to display is multiple images
Rails 5.2.4.3 ruby 2.5.1 mysql 14.14 view is implemented in haml
This time we want to display the information on the item details page
, so we use the ʻitems controller show action`.
items.controller.rb
class ItemsController < ApplicationController
#abridgement
def show
@item = Item.find(params[:id])
end
#abridgement
Explanation) First, search the id of the path of the ʻItem model with the find method, and create an instance of the product (item) that belongs to the corresponding id. `← I'm sorry if it's hard to understand ...
Based on the instance created here, extract information from the database.
If the information stored in the database is like the image above, you can display it in the view by specifying = @ item. Column name
.
For example, if you want to display the information in the name column, you can do as follows.
show.html.haml
%h2.item-show-page__item-name
= @item.name
This time, I want to display multiple images stored in the item_images table, which is associated with the items table.
show.html.haml
- @item.item_images.each do |image|
= image_tag image.image.url
Explanation) First, convert the item_images table that is associated with the item s table (@item) to the block variable image. Next, using ʻimage_tag, call the image of the block variable image (item_images table) converted earlier and add
.url`.
This .url
is required when selecting information from the database and displaying it in the view. If there is no .url
, the image URL stored in the database will be displayed in view.
The rest is iterative processing with the ʻeach statement`.
This time I posted about how to display the information stored in the database in the view. It is no exaggeration to say that this is the method that is always used when developing applications with Rails, so please refer to it.
Thank you for reading through to the end!
Recommended Posts