导轨的ActiveRecord找到控制台 [英] rails ActiveRecord find in console
问题描述
当我在Rails 3.2的控制台,我可以做到这一点就好了:
When I'm in the Rails 3.2 console, I can do this just fine:
p = Person.last
p.last_name
和它打印的姓。
但是当我尝试用 ID
找到它,它是能够找到一个
记录并将其存储在我的变量 P
,但我不能打印姓氏
柱。例如:
But when I try to find it by the id
, it's able to locate the single
record and store it in my variable p
, but I can't print the last_name
column. For example:
p = Person.where(id: 34).limit(1)
印刷 P
这里显示了所有的列,但 p.last_name
表示,这
printing p
here shows all the columns but p.last_name
says this
NoMethodError: undefined method `last_name' for
#<ActiveRecord::Relation:0x000000055f8840>
任何帮助将是AP preciated。
any help would be appreciated.
推荐答案
A 其中,
查询将返回一个<一个href="http://api.rubyonrails.org/classes/ActiveRecord/Relation.html"><$c$c>ActiveRecord::Relation$c$c>,样的作用就像一个数组,即使你限制返回的记录数。
A where
query will return an ActiveRecord::Relation
, which sort of acts like an array, even if you limit the number of returned records.
如果您而不是改变你的查询:
If you instead change your query to:
p = Person.where(id: 34).first
它将为你想要的,AREL知道了自动限制查询到一个结果,所以你不必明确指定限制(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.
和预期它会返回一个记录。
and it will return a single record as expected.
编辑:A其中查询将返回一个ActiveRecord ::关系,为 @mu太短在注释中提到的。
A where query returns an ActiveRecord::Relation, as @mu is too short mentioned in comments.
这篇关于导轨的ActiveRecord找到控制台的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!