如果我有一个带默认范围的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,对吧?
给定一个带有default_scope的模型来过滤所有过时的条目:
# == Schema Information
#
# id :integer(4) not null, primary key
# user_id :integer(4) not null, primary key
# end_date :datetime
class Ticket < ActiveRecord::Base
belongs_to :user
default_scope :conditions => "tickets.end_date > NOW()"
end
Run Code Online (Sandbox Code Playgroud)
现在我想得到任何票.在这种情况下,with_exclusive_scope是要走的路,但这种方法是否受到保护?只有这个有效:
Ticket.send(:with_exclusive_scope) { find(:all) }
Run Code Online (Sandbox Code Playgroud)
有点黑客,不是吗?那么正确的使用方法是什么?特别是在处理协会时,情况变得更糟(假设用户有很多票):
Ticket.send(:with_exclusive_scope) { user.tickets.find(:all) }
Run Code Online (Sandbox Code Playgroud)
这是如此丑陋! - 不能成为轨道!?