rails ActiveRecord在控制台中找到

当我在Rails 3.2控制台中时,我可以做到这一点:

p = Person.last p.last_name 

并打印姓氏。

但是当我尝试通过id找到它时,它能够找到单个记录并将其存储在我的变量p ,但是我无法打印last_name列。 例如:

 p = Person.where(id: 34).limit(1) 

这里打印p显示所有列,但p.last_name说明了这一点

 NoMethodError: undefined method `last_name' for # 

任何帮助,将不胜感激。

查询将返回一个ActiveRecord::Relation ,即使您限制返回的记录数,它也会像数组一样运行。

如果您改为将查询更改为:

 p = Person.where(id: 34).first 

它将按您的意愿工作,并且arel知道自动将查询限制为单个结果,因此您不必显式指定limit(1)

你也可以改为

 p = Person.find(34) # Throws an ActiveRecord::RecordNotFound exception if Person with id 34 does not exist 

要么

 p = Person.find_by_id(34) # Returns nil if Person with id 34 does not exist. Does *not* throw an exception. 

并且它将按预期返回单个记录。

编辑:其中查询返回ActiveRecord :: Relation,因为注释中提到的@mu太短 。

这将返回活动记录对象的集合:

 p = Person.where(id: 34).limit(1) 

但是只有一个id = 34,所以它是1的集合。

这样做的方法是:

 p = Person.where(id: 34).limit(1).first 

或更好:

 p = Person.where(id: 34).first 

或者,甚至更好:

 p = Person.find(34) 

你可能正在寻找的是

 @person = Person.find(34) @person.last_name 

在您的情况下,Person是一个类,它inheritance自ApplicationRecord

 p = Person.where(id:10).limit(1) 

它只返回查询的结果而不是对象。

你可以用它来检查

 p.class # => It reurns Nilclass which means its not at all a class 

所以你不能在p上使用p.last_name或p.first_name。