添加查找条件Rails中所有的活动记录模式 [英] Adding find condition to all Active Record Models in Rails

查看:155
本文介绍了添加查找条件Rails中所有的活动记录模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

反正是有添加查找条件的所有活动记录模式?

Is there anyway to add a find condition to all Active record models?

这是我想这个查询

ExampleModel.find :all, :conditions=> ["status = ?", "active"]

有同样的表现方式

to behave the same way as

ExampleModel.find :all

在每一个模型

谢谢!

推荐答案

您可以使用<一个href="http://api.rubyonrails.org/classes/ActiveRecord/Base.html#M002313"><$c$c>default_scope:

class ExampleModel < ActiveRecord::Base
  default_scope :conditions => ["status = ?", "active"]
end

如果你想使用这个在所有车型,您可以子类的ActiveRecord :: Base的并从您的所有车型(可能不顺利获得单表继承):

If you want to use this in all your models, you can either subclass ActiveRecord::Base and derive from that in all your models (probably doesn't work well with single-table inheritance):

class MyModel < ActiveRecord::Base
  default_scope :conditions => ["status = ?", "active"]
end
class ExampleModel < MyModel
end

...或者你可以设置 default_scope 的ActiveRecord :: Base的本身(可能是讨厌的,如果你决定一个模型不应​​该有此默认范围):

...or you could set the default_scope on ActiveRecord::Base itself (could be annoying if you decide that one model should not have this default scope):

class ActiveRecord::Base
  default_scope :conditions => ["status = ?", "active"]
end
class ExampleModel < ActiveRecord::Base
end

作为评论提到klochner,你可能还需要考虑增加一个 named_scope 的ActiveRecord :: Base的,名为主动,例如:

class ActiveRecord::Base
  named_scope :active, :conditions => ["status = ?", "active"]
end
class ExampleModel < ActiveRecord::Base
end
ExampleModel.active  # Return all active items.

这篇关于添加查找条件Rails中所有的活动记录模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆