scope

作者: kamionayuki | 来源:发表于2015-06-07 12:50 被阅读50次

scope一般用在model中

  • default_scope
    设置了default_scope后,每次调用model,都会先查询出scope的结果集,然后再该结果集上进行操作。
class Order < ActiveRecord::Base
    default_scope -> { order(created_at: :desc) }
end

此时调用Order.all,会把order按照created_at这个字段进行倒序排列。
如果有多个default_scope,那么这些default_scope会一起生效

class Order < ActiveRecord::Base
      default_scope -> { order(created_at: :desc) }
      default_scope -> { where(price: 100..1000) }
end

此时调用Order.all,则会把price在100到1000之间的order查询出来,然后再按照created_at这个字段进行倒序排列。

  • scope
    看下面的代码

    class Order < ActiveRecord::Base
      scope :today, -> { where(created_at: Time.now.midnight..(Time.now.midnight + 1.day)) }
    

end

`Order`中定义了一个`today`的`scope`,如何调用这个`scope`?
```ruby
Order.today

这样就可以了。感觉scope相当于一个类方法

class Order < ActiveRecord::Base
  private
  def self.today
    Order.where(created_at: Time.now.midnight..(Time.now.midnight + 1.day))
  end
end

相关文章

网友评论

      本文标题:scope

      本文链接:https://www.haomeiwen.com/subject/lyadqttx.html