How to return an empty ActiveRecord relation?

前端 未结 9 1893
有刺的猬
有刺的猬 2020-12-07 07:38

If I have a scope with a lambda and it takes an argument, depending on the value of the argument, I might know that there will not be any matches, but I still want to return

9条回答
  •  北海茫月
    2020-12-07 08:09

    Coming in Rails 4

    In Rails 4, a chainable ActiveRecord::NullRelation will be returned from calls like Post.none.

    Neither it, nor chained methods, will generate queries to the database.

    According to the comments:

    The returned ActiveRecord::NullRelation inherits from Relation and implements the Null Object pattern. It is an object with defined null behavior and always returns an empty array of records without quering the database.

    See the source code.

提交回复
热议问题