我有以下序列化程序
在我的图片表中,我的数据为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 :(得分:0)
您收到错误Called id for nil, which would mistakenly be 4 --
,因为
Images.where(post_id: id)
为[{1}}返回[]
,如果您id = 5
,则输出为[].first
所以,到目前为止,nil
为image_id
现在,当你执行nil
。id时,它会抛出异常而从nil
开始,它会按照规定发出警告。
有关此例外的更多信息,请参阅此博客:http://blog.bigbinary.com/2008/06/23/why-the-id-of-nil-is-4-in-ruby.html
你的方法应该是:
nil.object_id happens to be 4
答案 1 :(得分:0)
请改为image_id = Images.where(post_id: id).first
待办事项
image_id = Image.where(post_id: id).first
您写错了型号Images
它是复数
使用rails时
单数形式
代表型号Image
注意:您必须在此行之前设置id
值
答案 2 :(得分:0)
替换
image_id.nil?
与
image_id.present? (As always to check object)