你能帮我解决这个问题吗?我有一个名为Person的模型,它有两个名为name和surname的字段 我有两条记录是什么相同,但当被称为Person.find_by(名称:'fernando')给我显示一条唯一的记录,但在数据库中有两条相同的记录
<Person id: 1, name: "fernando", surname: "barroso", created_at: "2014-07-09 15:15:47", updated_at: "2014-07-09 15:15:47">
<Person id: 4, name: "fernando", surname: "barroso", created_at: "2014-07-09 15:34:01", updated_at: "2014-07-09 15:34:01">
这是否必须返回一组对象?
2.0.0-p481 :033 > Person.all
Person Load (0.4ms) SELECT "people".* FROM "people"
=> #<ActiveRecord::Relation [#<Person id: 1, name: "fernando", surname: "barroso", created_at: "2014-07-09 15:15:47", updated_at: "2014-07-09 15:15:47">, #<Person id: 2, name: "juan", surname: "perez", created_at: "2014-07-09 15:19:39", updated_at: "2014-07-09 15:19:39">, #<Person id: 3, name: "juan", surname: "pepe", created_at: "2014-07-09 15:23:06", updated_at: "2014-07-09 15:23:06">, #<Person id: 4, name: "fernando", surname: "barroso", created_at: "2014-07-09 15:34:01", updated_at: "2014-07-09 15:34:01">]>
2.0.0-p481 :034 > user= Person.find_by(name:'fernando')
Person Load (0.4ms) SELECT "people".* FROM "people" WHERE "people"."name" = 'fernando' LIMIT 1
=> #<Person id: 1, name: "fernando", surname: "barroso", created_at: "2014-07-09 15:15:47", updated_at: "2014-07-09 15:15:47">
答案 0 :(得分:4)
如何使用...方法
检索多条记录find_by
你没有。 that method的明确目的是找到与给定条件匹配的第一个记录。
Model.find_by找到匹配某些条件的第一条记录。例如:
Client.find_by first_name: 'Lifo'
......相当于写作:
Client.where(first_name: 'Lifo').take
如果要检索多条记录,请使用where
:
Person.where(name: 'fernando')
答案 1 :(得分:0)
默认情况下,如果您使用find_by
,Rails将仅返回第一个项目。如果你真的想要获得所有项目,你需要使用where
Person.where(name: 'fernando')
实际上,find_by
是where(conditions).first