我想在:limit
添加delete_all...
条款,我该怎么做?
我能想到的一种方法是覆盖默认的delete_all
,但我无法使其工作...... add_conditions!
函数未定义!
答案 0 :(得分:4)
无需覆盖任何内容:
# Rails 2
SomeModel.scoped(:limit => 10).destroy_all
# Rails 3
SomeModel.limit(10).destroy_all
修改:传递规范:
it "should destroy all using scope" do
10.times { SomeModel.create }
expect {
SomeModel.limit(5).destroy_all
}.to change(SomeModel, :count).by(-5)
SomeModel.count.should == 5
end
答案 1 :(得分:1)
这适用于mysql和rails 2.3
# in config/initializers/active_record_extensions.rb
class ActiveRecord::Base
# like delete_all, but honors limit (either through scope ar as a option)
def self.delete_all_limit(conditions = nil, limit=nil, offset=nil)
scope = scope(:find)
sql = "DELETE FROM #{quoted_table_name} "
add_conditions!(sql, conditions, scope)
add_limit!(sql, {:limit => limit, :offset => offset}, scope)
connection.delete(sql, "#{name} Delete all limited")
end
end
对于oracle_enhanced adpater而言,这是一个更加丑陋的黑客攻击。 (我认为使用rails3会更好)
# in config/initializers/active_record_extensions.rb
module ActiveRecord
class Base
# like delete_all, but honors limit and offset (either through scope ar as a option)
def self.delete_all_limit(conditions = nil, limit=nil, offset=nil)
scope = scope(:find)
q = self
limit ||= scope[:limit] if scope
if limit
limit = limit.to_i
q = q.scoped(:conditions => "rownum <= #{limit}")
end
return q.delete_all(conditions)
end
end
end