forked from eifion/asciicasts.com-translations
-
Notifications
You must be signed in to change notification settings - Fork 0
/
en.html
executable file
·35 lines (33 loc) · 1.88 KB
/
en.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<p>In this episode we’ll talk about <code>with_scope</code>. Below is a <code>Task</code> model that has a class method that returns all of the incomplete tasks.</p>
<pre class="ruby">
class Task < ActiveRecord::Base
belongs_to :project
def self.find_incomplete
find_all_by_complete(false, :order => 'created_at DESC')
end
end
</pre>
<p>This method is used in the <code>TasksController</code>.</p>
<pre class="ruby">
class TasksController < ApplicationController
def index
@tasks = Task_find_incomplete
end
</pre>
<p>This is a little limiting as we can’t add conditions to the custom <code>find</code> method to find, say, the first twenty incomplete tasks. What we want to do is something like</p>
<pre class="ruby">@tasks = Task_find_incomplete :limit => 20</pre>
<p>One way to do this is to add an options hash to the <code>find_incomplete</code> method in the model and merge it with the options in the find, but a more elegant solution exists with <code>find_scope</code>, passing the <code>find</code> options.</p>
<pre class="ruby">
class Task < ActiveRecord::Base
belongs_to :project
def self.find_incomplete(options = {})
with_scope :find => options do
find_all_by_complete(false, :order => 'created_at DESC')
end
end
end
</pre>
<p>Any <code>find</code> executed within the <code>with_scope</code> block will automatically inherit the specified options. Now the <code>find_incomplete</code> can take any conditions passed. This will also work within another scope. Our custom method is called in the <code>ProjectsController</code>. We can pass a limit condition here as well. This <code>find</code> passes through two scopes: first the incomplete tasks are found within the scope of the specified project and secondly they are limited to the first twenty.</p>
<pre class="ruby">
@tasks = @project.tasks.find_incomplete :limit => 20
</pre>