class Task < ActiveRecord::Base
belongs_to :project
def self.find_incomplete find_all_by_complete(false, :order => 'created_at DESC') end end
--------------------------------------------------------
class TasksController < ApplicationController
def index
@tasks = Task.find_incomplete end
这两段代码的作用是调用find_incomplete方法,返回项目中未完成的任务并按照创建时间降序
这个方法很好但有个局限,就是我们不能限制返回的数据,我们可以用with_scope.修改代码如下:
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
--------------------------------------------------------
@tasks = @project.tasks.find_incomplete :limit => 20
这样就成功实现了所有未完成任务的前20个