2017-10-21 46 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! –

相关问题