[Ruby] How to embed a youtube video in Rails (you can get the URL you entered even by editing)

3 minute read

1 overview

I wanted to display a youtube video embedded in rails, so I tried to implement it by referring to various articles. However, I could not implement it as I imagined according to the reference article. After repeating trial and error, I found how to generate the URL entered on the edit screen without any bugs, so I will describe how to implement it.

1.1 Types of YouTube URL

@Youtube videos are identified by a 11-digit character string. If you paste the 11-digit string into the URL for embedding on youtube, the embedded video will be displayed even on rails.

~~~: Youtube URL https://www.youtube.com/watch?v=0CqFEDzDkIA&t The video is identified by this character string → → “0CqFEDzDkIA&t” ~~~

However, there is a big pitfall here. As a condition for generating the above URL, the above URL will be generated only when

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

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

-URL of the video that stopped playing - URL of the video playing the video in special circumstances (Example: Get the URL from the playback screen of your favorite video, etc.)

(There may be others, but the URL will be generated in the longest direction anyway)

Based on these, I will explain the implementation setup.

2. Implementation

Author’s version

  • ruby 2.5.1
  • rails 5.2.3
  • mysql 5.7

2.1 Preparation

First, let’s create a sample app that only posts YouTube videos.

Terminal operation

$ mkdir projects // Directories are prepared
$ cd projects
$ mkdir sample_app
$ cd sample_app
$ $ rails new youtubetest -d mysql

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

$ rails s

Start the server. Go to http://localhost:3000 to see if you can launch the server. The startup is complete when the usual image appears. aa42578496e362131452b38405a24c75.png

2.2 Gem introduction

Since I often write in Haml, I will introduce gem'haml-rails'.



After installation, please drop rails Cut down and perform 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 the controller.


$ rails g controller products

Please add the following to the products controller.

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

  def new
    @product = Product.new

  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 the model.


$ rails g model product

Add the following to your migration file


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

Let’s do rails:db:migrate.


$ rails db:migrate

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

Create a view file for the top screen. 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.


  [email protected] do |product|
      = product.name
      %iframe{src: "https://www.youtube.com/embed/#{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. https://www.youtube.com/embed/ By adding #{post.youtube_url[32..42]} after this code, it will be possible to play normally even with the URL generated in an irregular state.

Supplementary explanation

 %iframe{src: "https://www.youtube.com/embed/#{product.youtube_url[32..42]}", omitted below}
# Add the code below
# Get the 11 digit string that identifies the video

Next, create views for the posting screen and the editing screen. Add the following code to new.html.haml and edit.html.haml` (You can 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'

The above is completed!! By adding a bit of code to the embed code, you can embed the video correctly in any URL (limited to youtube) and you can play the video.

Reference article

  • https://qiita.com/Kairi_Yasunnde/items/8e931a4670549ba8237e
  • https://qiita.com/yuichisan65/items/9356a2822fb37e51b3b4


Above, I would like to finish the explanation of “How to embed and display youtube video with Rails”. If you have any mistakes, please point me out.

Thank you for visiting our website.