新手问题 用 where 查找出来的类型为 ActiveRecord::Relation,但需要 model 实例,求帮助

Catherine · 2015年12月07日 · 最后由 torubylist 回复于 2015年12月08日 · 1696 次阅读

需要 2 个字段来查找记录,所以写了

a = Person.where(age: "#{age}", name: "#{name}")

找出的 a 的类型却是一个

ActiveRecord::Relation

而我需要的是一个 Person 实例,再使用 a.update 之类的方法操作。该怎么办?

each 方法可以用。

#1 楼 @chenge 谢谢!解决了。因为本身只有一条记录,就没有去用 each

如果你确定需要找的是单条记录的话,用 find_* 吧;where 返回的是 ActiveRecord::Relation,是 lazy 的,以便后面继续跟条件之类的。

where().first 也可以

但是你怎么保证出来的就只有一个 person?所以用.first 会好点吧?

find_by是一个,或 nil.

where().first没有数据的时候会 NPE

#6 楼 @qinfanpeng #5 楼 @cqcn1991

谢谢各位回复!我需要两个维度来定位一个或多个数据,用个 nil 判断一下再处理就够了

简单条件find_by(finds the first record matching some conditions),无order时等价于where().first,比较简单;复杂的where().take(retrieves a record without any implicit ordering) or where().first(finds the first record ordered by the primary key) or where().last(finds the last record ordered by the primary key). 具体参考 rails guides

find_by

如果想同时查询 first_name 和 locked 字段,可以用 and 把两个字段连接起来,获得所需的查询方法,例如 Client.find_by_first_name_and_locked("Ryan", true)。

需要 登录 后方可回复, 如果你还没有账号请 注册新账号