【问题标题】:rails 3 find single record from active record collectionrails 3 从活动记录集合中查找单个记录
【发布时间】:2013-08-03 16:33:22
【问题描述】:

我正在使用 rails v3.0.9

我不知道如何在活动记录集合中使用 find 方法

我在控制台中尝试过的,

@customers = Customer.all       # returns collection of records

@customer = @customers.find {|customer| customer.id == 1 } # returns the correct record

现在我在关联集合中使用相同的查找方法

@projects = @customer.projects # returns collection of Project records

@project = @projects.find {|project| project.id == 1 }  # got error
    ActiveRecord::RecordNotFound: Couldn't find Project with ID=1...

请任何人解释 find 方法与上述两个示例有何不同

有没有其他方法可以在关联集合中查找记录?

我使用数组检测来获取我的项目记录

@project = @projects.detect {|project| project.id == 1 }    # returns the correct record

哪种方法最好从活动记录数组中找到单个记录?

【问题讨论】:

    标签: ruby-on-rails-3 activerecord associations


    【解决方案1】:

    只需这样做:

    @customer = Customer.find(customer_id)
    

    例如:

    @customer = Customer.find(1)
    # => will return the customer with the id equal to 1
    

    【讨论】:

      【解决方案2】:

      你有几个机会:

      # this returns the customer with the id 1 - if a customer with id 1 exists!
      @customer = Customer.find(1)
      @customer = Customer.where(:id => 1).first
      
      # this returns the project with id 1 and customer_id = @customer.id
      @customer.projects.find(1)
      @customer.projects.where(:id => 1).first
      

      您的错误简单意味着您没有 id = 1 且 customer_id = @customer.id 的项目

      要回答您的问题..您应该使用 where 查询..这是新的 rails 3 方式。所有 find 方法在 rails 4 中都已弃用,并从 rails 核心中提取到额外的 gem 中。

      【讨论】:

      • 它很好,但 Model.find 和 Model.where 子句将执行数据库查询,其中数组方法 find 和检测将通过迭代返回一个对象(无查询),所以我尝试 Array 方法
      • 什么意思?如果您在数据库中保存了对象,您总是必须查询它们,才能将它们从数据库中取出:-)..
      • 假设我们的表中有最少的记录(5 条记录),并且想将每个对象存储在单独的变量中以供进一步计算,最好使用数组方法 find 和 detection 而不是 ActiveRecord where 和 find。例如stackoverflow.com/questions/17503221/…
      猜你喜欢
      • 1970-01-01
      • 2013-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-16
      • 1970-01-01
      • 2016-07-07
      相关资源
      最近更新 更多