开发者

ActiveRecord: How do I add NOLOCK?

开发者_高级运维I need to add "WITH NOLOCK" when using ActiveRecord? I know there is a way to do it nHibernate, but couldn't figure this out in ActiveRecord.

Thank you for your help. Regards,


Not to revive an old post. But there is an option to lock per query rather than setting it in the model.

For Example:

Account.where("name = 'shugo'").lock(true).first

Check out this link for more info. http://api.rubyonrails.org/classes/ActiveRecord/Locking/Pessimistic.html


I know this is old, but here is the answer:

criteria.SetLockMode(NHibernate.LockMode.None);


Just using :lock => 'WITH (NOLOCK)' in query works with current versions of activerecord-sqlserver-adapter (2.3.24 and 3.2.10 at the time of writing).

If you want it to be added to all queries for particular model, just put

default_scope :lock => 'WITH (NOLOCK)'

in your model.


Add this to your activerecord model

default_scope joins('WITH (NOLOCK)')

Do NOT do :lock => 'with (NOLOCK)' it will lock each row with "WITH(ROWLOCK,UPDLOCK)"


module ActiveRecord
  module ConnectionAdapters
     class SQLServerAdapter  < AbstractAdapter

         alias :old_raw_select :raw_select

         def raw_select(sql, name = nil)
            sql.gsub! %r{FROM\s\[(\w+)\]\s}im, "FROM [\\1] with (nolock)"
            old_raw_select(sql,name)
         end
      end
   end
end


default_scope {
    lock('WITH (NOLOCK)')
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜