2013-10-17 32 views
1

我有以下的串行轨道4名为id的零,这将被错误地4 - 如果你真的想零的ID,请使用OBJECT_ID

在我的形象表我有ID的数据 - 1, 2,3,4

如果我通过ID在我的串行5而不是抛出空的结果是抛出异常,因为

Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id 

为什么会发生这种情况,我该如何解决这个问题。

def image_ids 
    image_id = Images.where(post_id: id).first 
    unless image_id.nil? 
    image_id = image_id.id 
    [image_id] 
    end 
end 
+0

'Images.where(POST_ID:ID).first'是零,这就是所有 – apneadiving

+0

@apneadiving对不起,我不能让你.. – overflow

+0

他的意思是你的数据库查询没有产生任何结果。你无法得到任何东西的ID。您首先需要检查查询是否有任何结果,然后您可以返回该ID,否则返回任何(无) – KappaNossi

回答

0

你所得到的错误Called id for nil, which would mistakenly be 4 --因为

Images.where(post_id: id)回报[]id = 5如果你这样做[].first然后输出将是nil

因此,直到此时你image_idnil

现在当你做nil .id时,它会抛出异常并且从nil.object_id happens to be 4,它声明如上所述。

有关这个例外,你可以参考这个博客的更多信息:http://blog.bigbinary.com/2008/06/23/why-the-id-of-nil-is-4-in-ruby.html

你的方法应该是:

def image_ids 
    image_object = Images.where(post_id: id).first 
    unless image_object.blank? 
    image_id = image_object.id 
    [image_id] 
    end 
end 
0

试试这个image_id = Images.where(post_id: id).first

image_id = Image.where(post_id: id).first

你写错型号名称Images

它的复数

而轨使用

单数形式

的型号名称Image

注:你这行之前设置id

0

更换

image_id.nil? 

image_id.present? (As always to check object) 
相关问题