ruby-on-railsrubyyoutubeoembedvideo-embedding

How to used Oembed to embed a youtube thumbnail/title to Index page with RoR


I'm quite new to ruby on rails and I was hoping to get some help. I've been able to figure out how to embed a youtube clip in to my show page and have the title show

Show View

#video_show
  %h1= @youtube.title.html_safe 
  %p.username
    Shared by
    = @video.user.name
    about
    = time_ago_in_words(@video.created_at)
  .clearfix
    .video_image_show
      = @youtube.html.html_safe

Video Controller

def index
    @videos = Video.all.order("created_at DESC").paginate(page: params[:page], per_page: 20)
    @video.link = Video.find(params[:id])
    @youtube = OEmbed::Providers::Youtube.get(@video.link)


end

def show
     @infos = Info.where(video_id: @video)
     @comments = Comment.where(video_id: @video)
     @random_video = Video.where.not(id: @Video).order("RANDOM()").first
     @youtube = OEmbed::Providers::Youtube.get(@video.link)
end

But then it comes to showing the Thumbnail and title in my index page, it tells me that I have a undefined method such as 'title'.

index View

- @videos.each do |video|
    .Video
        .Video_image
            = image_tag @youtube.thumbnail_url.html_safe, video
        .Video_content
            .title
                %h2= @youtube.title.html_safe, video
            .data.clearfix
                %p.username
                    Shared by
                    = video.user.name

Is there anyway that I can link the video id to the index page which will allow the Oembed to show the @youtube = OEmbed::Providers::Youtube.get(@video.link) thumbnail and title ?

thanks so much in advance


Solution

  • You cannot set @youtube in the index method of your controller because at that moment you have an array of videos. What you need to have is something like:

    in your controller

    def index
        @videos = Video.all.order("created_at DESC").paginate(page: params[:page], per_page: 20)
    end
    

    and in your HAML view

    - @videos.each do |video|
        - youtube = OEmbed::Providers::Youtube.get(video.link)
        .Video
            .Video_image
                = image_tag youtube.thumbnail_url.html_safe, video
            .Video_content
                .title
                    %h2= youtube.title.html_safe, video
                .data.clearfix
                    %p.username
                        Shared by
                        = video.user.name