Adding parameter to a scope

前端 未结 5 1628
长情又很酷
长情又很酷 2021-02-03 23:38

I have a ActiveRecord query for example like this:

@result = stuff.limit(10)

where stuff is a active record query with where clauses, order by,

5条回答
  •  面向向阳花
    2021-02-04 00:13

    The scope would look like any other (although you may prefer a class method), e.g.,

    class Stuff < ActiveRecord::Base
      def self.lim
        limit(3)
      end
    end
    
    > Stuff.lim.all
    => [#,
     #,
     #]
    > Stuff.all.length
    => 8
    

    If you always (or "almost" always) want that limit, use a default scope:

    class Stuff < ActiveRecord::Base
      attr_accessible :name, :hdfs_file
    
      default_scope limit(3)
    end
    
    > Stuff.all
    => [#,
     #,
     #]
    > Stuff.all.length
    => 3
    

    To skip the default scope:

    > Stuff.unscoped.all.size
    => 8
    

提交回复
热议问题