rails ActiveRecord在控制台中找到

时间:2012-05-19 01:28:15

标签: ruby-on-rails ruby-on-rails-3 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:0x000000055f8840>

任何帮助将不胜感激。

4 个答案:

答案 0 :(得分:12)

where查询将返回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 is too short

答案 1 :(得分:3)

这将返回一组活动记录对象:

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)

答案 2 :(得分:1)

你可能正在寻找的是

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

答案 3 :(得分:0)

在你的情况下,Person是一个类,它继承自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