0

我正在做一个迁移项目。想要将 rails 2.x 应用程序迁移到 3.x。我的活动记录有问题。

在 Rails 2.x 中:

arr=StorageUnit.find(:all, :conditions =>"type='Drawer'")

上面的代码将为我提供 Drawer 类型的所有记录。

arr.class
=> Array

在 Rails 3.x 中:

此处不推荐使用上述功能。所以我不得不使用

arr=StorageUnit.where("type='Drawer'")

上面的代码将为我提供 Drawer 类型的所有记录。

arr.class
ActiveRecord::Relation

我猜这是因为 Active Record 发生了变化。我的问题是我有一些基于此类的代码。

例如:

if arr.class== Array 
   do something
else
   do something
end

所以现在我已经把它改成了

if arr.class== ActiveRecord::Relation 
   do something
else
   do something
end

只是想知道是否有更好的解决方案或任何替代方法来解决它。我有很多地方他们用过这些东西。

编辑:

arr=StorageUnit.where("type='Drawer'").all

将类提供为 Array。我的目的是想知道什么时候不带后缀的代码可以给你提供所需的记录,而不是全部到底有什么用。?只是为了换班吗?谁能解释一下?

4

1 回答 1

2

StorageUnit.where简单地返回ActiveRecord关系。继续.all执行将执行 sql 并创建StorageUnit.

arr = StorageUnit.where(:type => 'Drawer').all

它作为关系返回有许多有趣的副作用。除其他外,您可以在执行之前组合范围:

StorageUnit.where(:type => 'Drawer').where(:color => 'black')

您可以查看生成的 sql 进行调试:

StorageUnit.where(:type => 'Drawer').to_sql

想象一下:

class StorageUnit < ActiveRecord::Base

  scope :with_drawer, where(:type => 'Drawer')
  scope :with_color, lambda { |c| where(:color => c) }

end

现在:

StorageUnit.with_drawer.with_color('black').first_or_create # return the first storage unit with a black drawer
StorageUnit.with_drawer.with_color('black').all # return all storage units with black drawers

该关系允许建立基础查询,甚至保存以供以后使用。 all和其他类似的修饰符对关系具有特殊意义,并触发数据库执行和模型实例的构建。

于 2013-07-09T05:23:50.807 回答