What's the point of using unscope in rails

时间:2016-10-20 18:52:38

标签: ruby-on-rails activerecord

What's the point of using unscope in rails.

In the examples here they use the following code

Article.where('id > 10').limit(20).order('id asc').unscope(:order)

# which gives
SELECT * FROM articles WHERE id > 10 LIMIT 20

# and this without unscope
SELECT * FROM articles WHERE id > 10 ORDER BY id asc LIMIT 20

But why not just remove the .order('id asc') part:

Article.where('id > 10').limit(20)

1 个答案:

答案 0 :(得分:6)

But why not just remove .order('id asc')

I would say, that one of the reasons, is that you might simply not have access to the original query, so the only way for you to "modify" it, is to use unscope.

For example,

Article.where('id > 10').limit(20).order('id asc')

might very well be a part of some external gem as some scope, so you have to work with it as is. And here is when unscope comes to the rescue.

相关问题