3

クエリが複数のレコードを返さないことを保証する 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

4 に答える 4

0

私があなたの質問を正しく理解しているなら、あなたは使うことができますlimit

Foo.where(:thing => 'this_should_be_uniq').limit(1)
于 2013-09-30T15:20:09.677 に答える
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)
于 2013-09-30T15:20:21.267 に答える
-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)
于 2013-09-30T15:25:29.660 に答える