2017-10-21 29 views
-1

這個讓我感到困惑。幾個星期後,我一直在抨擊它,並且無處可去。對不起,如果這是顯而易見的,我仍然是一個鐵路新手ish ...Unsplash對象方法可以從控制檯中獲得,但不能從視圖中獲得

該應用程序正在對Unsplash圖片服務進行API調用。

這樣的application_helper具有以下方法:

def show_photo(size) 
@photo = Unsplash::Photo.random(query:"cars")[:urls][size.to_sym] 
end 

視圖有以下內容:

<%= image_tag(show_photo('small'), height: "220", width:"220") %> 

和顯示精細。

問題是,當我想從主體中拉出一些其他方法。我已經添加的應用程序的另一種方法幫助這樣的:

def show_author 
    @photo.user.name 
end 

和相應的視圖: 攝影:<%= show_author%>

然後我得到這個錯誤: 未定義的方法`用戶「爲#

但是調用Rails的方法時安慰它工作正常:

@photo = Unsplash::Photo.random(query:"cars") 
=> #<Unsplash::Photo:0x00000004fcf950 @attributes=#<OpenStruct id="CKeoh- 
    90U3E", created_at="2017 ....... 

2.3.0 :003 > @photo.user.name 
=> "Florian Schneider" 

我需要做什麼才能在視圖中使用user.name?

非常感謝提前,

魯道夫

+0

希望您能回覆發佈的答案。 – theartofbeing

回答

1

@photo沒有照片,它看起來像你呼籲@photo一些元數據與[:urls][size.to_sym],你不能在上面打電話.user的元數據。

你基本上說Unsplash::Photo.random(query:"cars")[:urls][size.to_sym].user

您可能要做到以下幾點:

def photo 
@photo ||= Unsplash::Photo.random(query:"cars") 
end 

def resized_photo(size) 
photo[:urls][size.to_sym] 
end 

def photo_author_name 
    photo.user.name 
end 

BTW @photo ||=被memoizing API調用這樣你就不會犯同樣的電話多次。

+0

theartofbeing,謝謝你的回答,這工作絕對好!這完全是有道理的......對於遲到的答案抱歉,但出於專業原因,我離開了我的Mac! –

相關問題