Adding parameter to a scope

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

    Well Scopes are meant for this

    Scoping allows you to specify commonly-used Arel queries which can be referenced as method calls on the association objects or models. With these scopes, you can use every method previously covered such as where, joins and includes. All scope methods will return an ActiveRecord::Relation object which will allow for further methods (such as other scopes) to be called on it.

    Source: http://guides.rubyonrails.org/active_record_querying.html#scopes

    So if you feel that there are some common queries which you have, or you need some kind of chaining in your queries which are common to many. Then i will suggest you to go for scopes to prevent repetition.

    Now to answer how the scope will look like in your case

    class YourModel < ActiveRecord::Base
      scope :my_limit, ->(num) { limit(num)} 
      scope :your_where_condition, ->(num) { where("age > 10").mylimit(num) } 
    end
    

提交回复
热议问题