Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/53.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 返回关系而不是预期对象类型(模型人)的AR查询_Ruby On Rails_Activerecord - Fatal编程技术网

Ruby on rails 返回关系而不是预期对象类型(模型人)的AR查询

Ruby on rails 返回关系而不是预期对象类型(模型人)的AR查询,ruby-on-rails,activerecord,Ruby On Rails,Activerecord,基于使用“限制”或“第一个”返回不同对象类型的查询 此示例使用limit1,但不生成预期的对象类型: c = PersonCategory.where("category = ?", "Crown").limit(1) ## => PersonCategory Load (0.3ms) SELECT `person_categories`.* FROM `person_categories` WHERE (category = 'Crown') LIMIT 1 => [#<

基于使用“限制”或“第一个”返回不同对象类型的查询

此示例使用limit1,但不生成预期的对象类型:

c =  PersonCategory.where("category = ?", "Crown").limit(1) ##
=> PersonCategory Load (0.3ms)  SELECT `person_categories`.* FROM `person_categories` WHERE (category = 'Crown') LIMIT 1
=> [#<PersonCategory id: 1, category: "Crown">]  #####
c.class
=> ActiveRecord::Relation 
此示例使用first并给出所需的输出:

c =  PersonCategory.where("category = ?", "Crown").first ##
=> PersonCategory Load (0.4ms)  SELECT `person_categories`.* FROM `person_categories` WHERE (category = 'Crown') LIMIT 1
=> #<PersonCategory id: 1, category: "Crown"> 
c.class
=> PersonCategory(id: integer, category: string)   #####
ruby-1.9.2-p180 :034 > 
limit返回一组有限的结果。在您的例子中,它返回本质上是PersonCategory对象数组的内容,即使您仅使用limit1指定一个对象

例如,调用PersonCategory.limit15将返回数据库中的前15个PersonCategory项

首先,另一方面,只返回它前面查询的第一个结果,而不是结果数组。这就是为什么您会看到返回单个PersonCategory对象的原因