Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/52.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 未定义的方法'id';对于#<;ActiveRecord::关系[]>;_Ruby On Rails - Fatal编程技术网

Ruby on rails 未定义的方法'id';对于#<;ActiveRecord::关系[]>;

Ruby on rails 未定义的方法'id';对于#<;ActiveRecord::关系[]>;,ruby-on-rails,Ruby On Rails,我无法从模型中获取id值 我的代码: 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

我无法从模型中获取id值

我的代码:

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
session[“game\u space”]=params[:game\u space\u id]
@玩家空间=玩家空间。其中(游戏空间id:session[“游戏空间”],用户id:current用户id)

会话[“player_space”]=@player_space.id#您正在尝试获取ActiveRecord关系的
id
。试试这个:

@player\u space=PlayerSpace.where(游戏空间id:session[“游戏空间”],用户id:current\u user.id)。首先

然后获取
@player\u space的id

问题:

  • Where子句返回活动记录关系对象,该对象是一种数组(集合)。因此,您必须选择对象来调用id方法

    @player\u space=PlayerSpace.where(游戏空间id:session[“游戏空间”],用户id:current\u user.id)。首先

  • 您的查询结果/集合没有任何行/对象。因此,调用
    #first
    将返回nil。因此,
    nil#id
    将再次导致错误


希望你明白我的意思

您得到的是一个
ActiveRecord::Relation
类,而不是一个模型对象。您可以从关系中的项目获取id。如果您确定您将取回一件物品,您可以简单地执行以下操作:

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

如果您希望获得一条记录,那么放弃where和do find_by也是可以接受的。如果您希望获得一条记录,那么放弃where和do find_by也是可以接受的:
PlayerSpace.find_by(game_space\u id:session[:game_space],user_id:current_user.id)
我没有使用。首先,因为我只有一行。现在,我把它放在第一位,错误仍然发生。注意:如果我尝试:session[“player\u space”]=@player\u space.name有效。所以,我希望我不能访问id。。。我真的不知道。不管您有多少行,where子句都是用来返回某种集合对象的。因此,它将返回emply集合/数组,或者在集合中返回结果,但不会作为单个记录返回!可以在记录中调用#id方法。它是所需表格的列。因此,当预期输出为空或为零时。不能叫它。
PlayerSpace.where(game_space_id: session["game_space"], user_id: current_user.id).first