Rails Active Record方法确保查询返回单个记录?

时间:2013-09-30 15:15:59

标签: ruby-on-rails ruby activerecord

Active Record中是否存在确保查询不返回多条记录的内容?

这就是基本功能(道歉 - 这不是真正的代码,但足以让我知道我在寻找什么):

Foo.where(:thing => 'this_should_be_uniq').single

def single(records)
  if records.length > 1
    raise # or maybe return nil or something like that
  else
    return records.first
  end
end

基本上,这可以防止意外地(错误地)假设您的查询将始终返回单个记录。

谢谢!

4 个答案:

答案 0 :(得分:0)

如果我正确理解您的问题,您可以使用limit

Foo.where(:thing => 'this_should_be_uniq').limit(1)

答案 1 :(得分:0)

你可以做Foo.where(:thing =>'this_should_be_uniq')。single或Foo.where(:thing =>'this_should_be_uniq')。single或 .limit(1)

Foo.where(:thing => 'this_should_be_uniq').first
Foo.where(:thing => 'this_should_be_uniq').last
Foo.where(:thing => 'this_should_be_uniq').limit(1)

答案 2 :(得分:0)

我在ActiveRecord :: FinderMethods中找不到这样的方法。

作为替代解决方案,如果存在两个以上的记录,则在引发异常的情况下,可以使用tap方法将其写得更短:

Foo.where(:thing => 'this_should_be_uniq').tap { |r| raise "ERROR" if r.count > 1 }.first

考虑到与其他操作的隔离,以下代码是正确的:

Foo.where(:thing => 'this_should_be_uniq').to_a.tap { |r| raise "ERROR" if r.size > 1 }[0]

答案 3 :(得分:-1)

您也可以使用ActiveRecord find

Foo.find_by_thing('this_should_be_uniq')
Foo.find(:first, :conditions => {:thing => 'this_should_be_uniq'})

您还可以找到多个属性

Foo.find_by_attr1_and_attr2(attr1_value, attr2_value)