0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

HTMLの基礎知識(YoutubeのURL 投稿と反映)

Last updated at Posted at 2022-07-22

みなさん今日もプログラミングの学習お疲れ様です!!

今回はYoutudeの動画を投稿し、それを詳細ページに反映する機能を実装していきます!!:sunny:

Step1:モデルを作成
ターミナル
rails generate migration AddYoutubeUrlToTweets youtube_url:string
ターミナル
rails db:migrate
Step2:コントローラーの追加
tweets_controller.rb
 private
    def tweet_params
        params.require(:tweet).permit(:youtube_url)
    end
Step3:newにyoutude_urlのデータを追加
tweets_new.html.erb
<%= form_for @モデル名 do |f| %>
省略
  <%= f.label :youtube_url %>
    <%= f.text_field :youtube_url, :size => 140 %>
省略
<% end %>
Step4: helperにメソッドの定義
tweets_helper.erb
module TweetsHelper
  def find_youtube_url(youtube_url)
    if youtube_url[0..16] == "https://youtu.be/"
      return youtube_url[17..27]
      # "https://youtu.be/WGiUk8VakxQ" 11桁のyoutubeのURLが出力されるようにする
    else
      return youtube_url[32..42]
      # "https://www.youtube.com/watch?v=WGiUk8VakxQ" 11桁のyoutubeのURLが出力されるようにする
    end
  end
end
Step5:Viewにyoutude_urlを反映(show)
tweets_show.html.erb
<iframe width="560" height="315" src="https://www.youtube.com/embed/<%= find_youtube_url(@tweet.youtube_url) %>" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
Step6:Viewにyoutude_urlを反映(index)
tweets_show.html.erb
<% @モデル名.each do |t| %>
    <div class="tweet">
      省略
      <iframe width="560" height="315" src="https://www.youtube.com/embed/<%= find_youtube_url(t.youtube_url) %>" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
      省略
    </div>
  <% end %>

Step7:確認!!

スクリーンショット (63).png

以上です!!!

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?