【问题标题】:Rails Active Record method to ensure query returns single record?Rails Active Record 方法确保查询返回单条记录?
【发布时间】:2013-09-30 15:15:58
【问题描述】:

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

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

谢谢!

【问题讨论】:

  • 您只想要一条记录还是特别想要第一条记录?
  • .limit(2) 然后检查长度?但通常我会在数据库中创建唯一索引。
  • 如果您尝试这样做是因为您的应用程序的业务逻辑表明只有一个这样的东西应该存在,那么您几乎肯定最好在数据库中执行它(使用唯一索引,或触发器)而不是每次都检查。最好从一开始就防止坏数据,而不是编写代码,这样如果你得到坏数据,你的应用就不能再工作了。
  • @dax 只有一条记录。当有多个记录时引发。
  • @VictorMoroz 每次我想检查长度似乎有点麻烦。有关其他评论的回复,请参见下文。

标签: ruby-on-rails ruby activerecord


【解决方案1】:

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

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

【讨论】:

  • 我的问题略有不同。我想确保当我通过我已经组成“单”的方法进行选择时,查询返回单条记录。即对于某些地方,我想确保只有一条记录是匹配的(而限制只会确保我收到一条记录,无论是否有多个匹配项)。
  • 啊,我明白了...你能多谈谈你想如何使用它吗?取决于您在做什么,仅使用模型验证来实现唯一性不是更直接吗?
【解决方案2】:

你可以做 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)

【讨论】:

    【解决方案3】:

    我在 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]

    【讨论】:

      【解决方案4】:

      你也可以使用 ActiveRecord 查找

      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)
      

      【讨论】:

      • 这不能回答问题; OP 不需要知道如何找到东西,他们需要知道如何强制唯一性。
      • 我的第一部分回答了 OP 的问题。 find_by/find 只返回一条记录。正是OP一直在问什么。第二部分是一些额外的信息。
      • 它没有;问题不是“我如何得到一件事”,而是“如果有不止一件事情,我该如何提出(因为事情应该是独一无二的)”。
      • 是的。但是在我回答了这个问题后,OP 澄清了这一点。在此处查看其他答案。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多