#<ActiveRecord::Relation []> 的未定义方法`id' [英] undefined method `id&#39; for #&lt;ActiveRecord::Relation []&gt;

查看:34
本文介绍了#<ActiveRecord::Relation []> 的未定义方法`id'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法从模型中获取 id 值.

I can't get id value from a model.

我的代码:

session["game_space"]   = params[:game_space_id]

@player_space = PlayerSpace.where(game_space_id: session["game_space"], user_id: current_user.id)

session["player_space"] = @player_space.id #<<<<===== The error occurs here

redirect_to "show",:id => @player_space.id

错误信息:

Error: undefined method `id' for #<ActiveRecord::Relation []>

你能帮我解决这个问题吗?

Can you help me on this?

推荐答案

问题:

  • Where 子句返回活动记录关系对象,它是一种数组(集合).所以你必须选择对象来调用 id 方法.

  • Where clause returns active record relation object which is a kind of array (collection). So you have to pick the object to call the id method over it.

@player_space = PlayerSpace.where(game_space_id: session["game_space"], user_id: current_user.id).first

@player_space = PlayerSpace.where(game_space_id: session["game_space"], user_id: current_user.id).first

您的查询结果/集合没有任何行/对象.所以调用 #first 将返回 nil.所以结果 nil#id 会再次导致错误.

Your query results/collection doesn't have any row/object. So calling #first will return nil. So as a result nil#id will cause error again.

希望你明白这一点!

这篇关于#<ActiveRecord::Relation []> 的未定义方法`id'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆