0

我已经坚持了好几天了。在模型中,我定义了“代码”,它格式化要添加到 iframe 中的 youtube 链接。当我去 localhost:3000/videos 时,它给了我这个

“# 的未定义方法‘代码’”

<h1>Video Index</h1>
<% @videos.each do |video| %>
    <div class="table-bordered">
    <iframe width="560" height="349" src="<%= "http://www.youtube.com/embed/"+@videos.code %>"></iframe>
    </div>
<% end %>

现在,如果我跳转到显示页面(localhost:3000/videos/#),它可以正常工作。这是节目。

<div class="row">
    <div class="span8">
            <ol class="video">
                <iframe width="560" height="349" src="<%= "http://www.youtube.com/embed/"+@video.code %>"></iframe>
            </ol>
    </div>
</div>

我也没有看到控制器中的索引有问题。@videos = Video.all 看起来很简单。

class VideosController < ApplicationController

    def index
        @videos = Video.all
    end

    def show
        @video = Video.find(params[:id])
    end

这个模型。video.rb 我定义了代码的地方

class Video < ActiveRecord::Base
    has_many :comments
    belongs_to :user
    default_scope -> { order('created_at DESC') }
    validates :video, presence: true, length: { maximum: 420 }

    def code
      self.video.try(:split, '/').try(:last) || ''
    end
end

这是用户,即视频所属的用户

class User < ActiveRecord::Base
  has_many :videos

感谢任何回复的人的帮助,并确保给我一个代表点,这样我就可以在 15 岁时代表你回来;)

4

1 回答 1

2

@videos不应该有这样的方法code,它应该是一个实例方法。

您需要在循环内使用video而不是。@videos

此外,视图代码看起来像 PHPish。它需要改进。

重构

代替

<iframe width="560" height="349" src="<%= "http://www.youtube.com/embed/"+@videos.code %>">
</iframe>

尝试这个

# View
video_iframe video.code

# Helper
def video_iframe(src)
  content_tag(:iframe, width: 500, height: 349, src: src)
end

# Model
def code
  if process_video.present?
    "http://www.youtube.com/embed/#{process_video}"
  end
end

private
def process_video
  video.try(:split, '/').try(:last) || ''
end
于 2013-09-18T19:41:37.767 回答