每个语句和运行API都给我带来麻烦

时间:2012-02-17 21:50:08

标签: ruby-on-rails ruby ruby-on-rails-3 swish

我正试图通过Jeremys令人敬畏的运球库(https://github.com/jeremyw/swish)对运球进行前5次射门,获得他们的冠军,然后在视图中打印这些项目,但我保留得到错误:#。

的未定义方法`title'
@dribbbletimes = []
(1..5).each do |i| 
    @dribbbletimes << Dribbble::Shot.find(i).title 
end 

如果我用数字替换i,那么它可以找到没有问题的标题并打印5次。有没有猜到为什么会这样?

1 个答案:

答案 0 :(得分:2)

我刚刚尝试了你的代码,似乎find方法在找不到任何内容时返回不同类型的对象,因此当镜头号无效时调用title方法不起作用

例如:

1.9.2-p290 :017 > Dribbble::Shot.find(2)
 => #<Dribbble::Shot:0x007ff96b3ed110 @player=#<Dribbble::Player:0x007ff96b3ed048 @created_at="2009/07/21 19:32:24 -0400", @shots_count=172, @twitter_screen_name="owltastic", @avatar_url="http://dribbble.s3.amazonaws.com/users/4/avatars/original/Meagan-6.jpg?1309446649", @likes_received_count=14937, @name="Meagan Fisher", @location="Brooklyn, NY", @following_count=445, @likes_count=1080, @website_url="http://owltastic.com", @username="owltastic", @url="http://dribbble.com/owltastic", @rebounds_count=3, @draftees_count=44, @id=4, @drafted_by_player_id=1, @followers_count=9979, @comments_received_count=1795, @comments_count=211, @rebounds_received_count=13>, @created_at="2009/07/23 07:07:53 -0400", @short_url="http://drbl.in/c", @image_url="http://dribbble.com/system/users/4/screenshots/2/Picture-2.png?1309017100", @title="Playing with Dribbble", @likes_count=9, @rebound_source_id=nil, @url="http://dribbble.com/shots/2-Playing-with-Dribbble", @rebounds_count=0, @id=2, @image_teaser_url="http://dribbble.com/system/users/4/screenshots/2/Picture-2_teaser.png?1309017100", @height=300, @views_count=13299, @comments_count=2, @width=400> 

1.9.2-p290 :018 > Dribbble::Shot.find(3)
 => #<Dribbble::Shot:0x007ff96b3ced50 @created_at=nil, @message="Not found"> 

在将返回的对象添加到数组之前,您应该区分返回的对象是否真的有效。

<强>更新
在稍微挖掘一下后,我发现无效的镜头在created_at属性上返回一个nil值,所以你可能会这样做:

@dribbbletimes = []
(1..5).each do |i|
    shot = Dribbble::Shot.find(i)  
    @dribbbletimes << shot.title unless shot.created_at.blank? 
end