相关疑难解决方法(0)

覆盖Rails default_scope

如果我有一个带默认范围的ActiveRecord :: Base模型:

class Foo < ActiveRecord::Base

  default_scope :conditions => ["bar = ?",bar]

end
Run Code Online (Sandbox Code Playgroud)

有没有办法Foo.find 使用这些default_scope条件?换句话说,您可以覆盖默认范围吗?

我原以为在名称中使用'default'会表明它是可以覆盖的,否则会被称为类似的global_scope,对吧?

ruby-on-rails

150
推荐指数
8
解决办法
8万
查看次数

在Rails中覆盖default_scope

在我的Post.rb模型中,我有 default_scope :conditions => {:deleted => 'false'}

但如果我试图跑Post.find(:all, :conditions => "deleted='false'"),它将不会返回任何东西.就像default_scope优先于所有内容一样.

我想要它,以便当我这样做Post.find()时不会返回已删除的帖子,但我也希望能够在需要时访问它们.在我的查询或我的Rails模型中需要更改什么?

谢谢.

ruby-on-rails models default-scope

19
推荐指数
2
解决办法
8237
查看次数

Rails 3.1.3无范围范围

我已经看过很多关于这个的帖子,但似乎都没有解决我的问题.我有一个default_scope像这样的模型:

default_scope where(:is_active => true).order('LOWER(table.name)');
Run Code Online (Sandbox Code Playgroud)

我有其他(正常)范围,我想使用创建inactive范围unscoped.我想将它定义为范围,但只有在定义为类方法时才有效:

# works
def self.inactive
  unscoped { where(:is_active => false) }
end

# none of these work
scope :inactive, unscoped { where(:is_active => false) }
scope :inactive, with_exclusive_scope { where(:is_active => true) }
scope :inactive, unscoped.where(:is_active => false)
scope :inactive, lambda { unscoped { where(:is_active => false) } }
scope :inactive, unscoped { lambda { where(:is_active => false) } }
unscoped do
  scope :inactive, where(:is_active => false)
end
Run Code Online (Sandbox Code Playgroud)

有没有我错过的方法,或者我是否必须使用类方法来定义此范围?

activerecord ruby-on-rails default-scope ruby-on-rails-3.1

7
推荐指数
1
解决办法
2387
查看次数