How to embed and display youtube videos in Rails (You can also get the URL you entered by editing)

1 Overview

I wanted to embed and display youtube videos on rails, so I tried to implement it by referring to various articles. However, I couldn't implement it as I envisioned according to the reference article. After that, I repeated trial and error and found out how to generate the URL entered on the edit screen without any bugs, so I will describe how to implement it.

1.1 YouTube URL types

Youtube videos are identified by 11-digit character strings. If you paste the 11-digit character string into the URL for embedding on youtube, the embedded video will be displayed on rails as well.
Identify the video with this character string → → "0CqFEDzDkIA & t"

However, there is a big pitfall here. As a condition for the above URL to be generated, the above URL will be generated only when youtube video starts from 0 seconds </ font>. If this condition is not met, a longer URL will be generated, so even if you create it according to Reference article, the embedded video will be displayed. There will be a bug that will not be done.

If the URL meets the criteria, it will be played correctly in Reference article.

** If you get the youtube URL by the following method, a URL longer than the 11-character code for video identification will be generated **

-URL of the video that stopped playing the video --URL of the video playing the video in a special situation (Example: Get the URL from the playback screen of your favorite video, etc.) </ Font> (There may be others, but in any case the URL will be generated in the longer direction)

Based on these, we will explain the implementation setup.

2. Implementation

Author version

  • ruby 2.5.1
  • rails 5.2.3
  • mysql 5.7

2.1 Preparation

First, we will create a sample app that just posts YouTube videos.

Terminal operation

$ mkdir projects //Prepare your own directory
$ cd projects
$ mkdir sample_app
$ cd sample_app
$ $ rails new youtubetest -d mysql

If you want to specify the version, enter as follows rails -5.2.3- new youtubetest -d mysql

$ rails s

Start the server. Go to http: // localhost: 3000 to see if you were able to launch the server. If the usual image appears, the startup is complete. aa42578496e362131452b38405a24c75.png

2.2 Gem introduction

I often write in Haml, so I'll introduce gem'haml-rails'.


gem 'haml-rails'

After installation, please lower rails ** lower </ font> ** and bundle install.

2.3 Creating an app

Describe the routing.


Rails.application.routes.draw do
  root to: 'products#index'
  resources :products, only: [:index, :new, :create,:edit ,:update, :destroy]

Create a controller.


$ rails g controller products

Add the following to the products controller.

class ProductsController < ApplicationController
  def index
    @products = Product.all

  def new
    @product =

  def create
    redirect_to root_path

  def destroy
    product = Product.find(params[:id])

  def edit
    @product = Product.find(params[:id]) 

  def update
    product = Product.find(params[:id])

  def product_params
    params.require(:product).permit(:name, :youtube_url)

Create a model.


$ rails g model product

Add the following to the migration file


class CreatePosts < ActiveRecord::Migration[5.2]
  def change
    create_table :products do |t|
      t.text :name #add to
      t.string :youtube_url #add to

Let's do rails: db: migrate.


$ rails db:migrate

** Preparation is complete ** ** This is the most important process! !! ** **

Create a view file for the top screen. Please enter the following command.


$ touch app/views/products/index.html.haml
$ touch app/views/products/new.html.haml
$ touch app/views/products/edit.html.haml
* Please type in order from the top

Create a view file for the top screen. Add the following code to ʻindex.html.haml`.


  - @products.each do |product|
      %iframe{src: "{product.youtube_url[32..42]}",allow: "accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture", allowfullscreen: "", frameborder: "0", height: "315", width: "560"}

The code below is the base code for the embed code. By adding # {post.youtube_url [32..42]} to the end of this code, even URLs generated in an irregular state can be played normally.

Supplementary explanation

 %iframe{src: "{product.youtube_url[32..42]}", Omitted below}
#Add the code below
#Obtained an 11-digit character string that identifies the video

Next, create a view of the post screen and edit screen. Add the following code to new.html.haml and ʻedit.html.haml (It is okay to use a partial template in this process)



      = form_with(model: @product, local: true) do |form|
        = form.label :name, "name"
        = form.text_field :name, placeholder: 'name'

        = form.label :youtube_url, "YouTube URL"
        = form.text_field :youtube_url, placeholder: 'youtube_url'
      = f.submit 'Post'

** This is the end !! ** By adding a little description to the embed code, you can embed the video correctly in any URL (limited to youtube) and you can play the video.

Reference article



This concludes the explanation of "How to embed and display youtube videos in Rails". I would appreciate it if you could point out any mistakes.

Thank you for watching until the end.

Recommended Posts