我正在开展一个迁移项目。想将rails 2.x app迁移到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。我的目标是知道什么时候没有后缀的代码可以提供所需的记录,而不是最终使用的所有记录。这只是为了换班吗?谁能ecxplain?
答案 0 :(得分: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
和其他类似的修饰符对关系具有特殊意义,并触发数据库执行和模型实例的构建。