2014-01-17 43 views
1

進出口新的軌道,和我有一個視頻模式,控制器和視圖的應用程序。NoMethodError在歡迎#指數

林搞清楚如何在使用視頻控制器林要查詢並顯示我想要的視頻,到目前爲止,一切順利。

我有一個網頁,我想,所以我做了歡迎控制器與索引行動教程說來顯示一週中最重要的視頻。

裏面的歡迎控制器我有:

class WelcomeController < ApplicationController 

     def index 
     @highlighted_video = Video.where("highlight = true") 
     end 

    end 

亮點是一個布爾屬性。和索引視圖:

<iframe width="100%" height="315" src="<%= @highlighted_video.url %>" frameborder="0" allowfullscreen></iframe> 

但我得到以下錯誤(網址是我的分貝另一個視頻屬性):

 undefined method `url' for #<ActiveRecord::Relation::ActiveRecord_Relation_Video:0x2507760> 

我認爲這將已經在視頻控制器工作,但它不請你幫忙。

+1

你是否試圖獲得高亮值的第一條記錄爲真? – suren

回答

0

你不能叫上@highlighted_video
url方法在這個變量你有video

def index 
    @highlighted_video = Video.where("highlight = true") 
    end 

陣列上index.html.erb

<% @highlighted_video.each do |video| %> 
    <iframe width="100%" height="315" src="<%= video.url %>" frameborder="0" allowfullscreen></iframe> 
    <% end %> 
+0

我只是在尋找一個視頻,但我現在知道WHERE返回一個數組。如果我使用FIND方法怎麼辦? – user3099920

1

我會保持我的控制器骨感。假設我要回是高亮的第一條記錄,我想補充一個scopeVideo型號:

class Video < ActiveRecord::Base 
    # ... 
    scope :highlighted, -> { where(highlight: true).first } 
    # ... 
end 

這將返回是高亮的第一記錄。然後,在控制器我只想做:

class WelcomeController < ApplicationController 

    def index 
    @highlighted_video = Video.highlighted 
    end 

end 

然後在您的視圖代碼應該工作得很好,假設您已經定義在模型中#url方法。

+1

這就像一個魅力!教我主人 – user3099920

+0

@ user3099920很高興聽到!如果它解決了你的問題,你可能會接受*答案:) – Agis

1

如果你想獲得的第一條記錄試試這個

@highlighted_video = Video.where("highlight = true").first 

要小心,當你訪問@highlighted_video實例變量的屬性,如果沒有任何記錄匹配您的查詢,它將返回零值,在那裏你會得到錯誤的未定義的方法URL爲零類。