× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

Simplify your Rails controllers by using Named Scopes for frequent queries

Christoph Wagner
Jul 27, 2015
<p>If you have a specific query that you frequently run in your Rails app, you can simply define it as a class method on your model:</p> <pre><code class="language-ruby">class Article &lt; ActiveRecord::Base def self.published where(published: true) end end</code></pre> <p>If that's too complicated for you, Rails even offers a shortcut:</p> <pre><code class="language-ruby">class Article &lt; ActiveRecord::Base scope :published, -&gt; { where(published: true) } end</code></pre> <p>Which one you prefer is a matter of taste. Both are exactly equivalent. You can find more info on named scopes in the <a href="http://guides.rubyonrails.org/active_record_querying.html#scopes">Rails Guide</a>.</p>
comments powered by Disqus