如何使用find_by方法检索数据库中的多个记录

时间:2014-07-09 15:54:57

标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-4

你能帮我解决这个问题吗?我有一个名为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"> 

2 个答案:

答案 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_bywhere(conditions).first

的捷径