Adding parameter to a scope

前端 未结 5 1616
长情又很酷
长情又很酷 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:26

    There are indeed multiple ways of doing such, class methods are one as pointed out by @Dave Newton. If you'd like to use scopes, here's how:

    scope :max_records, lambda { |record_limit|
      limit(record_limit)
    }
    

    Or with the Ruby 1.9 "stabby" lambda syntax and multiple arguments:

    scope :max_records, ->(record_limit, foo_name) {   # No space between "->" and "("
      where(:foo => foo_name).limit(record_limit)
    }
    

    If you'd like to know the deeper differences between scopes and class methods, check out this blog post.

    Hope it helps. Cheers!

提交回复
热议问题