What is scope/named_scope in rails?

前端 未结 5 1069
耶瑟儿~
耶瑟儿~ 2020-12-02 04:08

I\'ve recently started an internship. My employer uses ruby on rails, and I frequently encounter new syntax that I need to look up to understand. I\'ve googled around for a

5条回答
  •  天涯浪人
    2020-12-02 04:55

    Scopes are nothing but class methods.

    Why use them?

    Scoping allows you to specify commonly-used queries(it can be considered as a shortcut for long or most frequently used 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.

    To define a simple scope, we use the scope method inside the class, passing the query that we'd like to run when this scope is called:

    class Article < ActiveRecord::Base
      scope :published, -> { where(published: true) }
    end
    

    This is exactly the same as defining a class method, and which you use is a matter of personal preference:

    class Article < ActiveRecord::Base
      def self.published
        where(published: true)
      end
    end
    

    Please follow the following link for full description with example. I hope this will help you.

    http://guides.rubyonrails.org/active_record_querying.html

提交回复
热议问题