#004_将查询移入模型类

根据DHH提出的DRY原则,我们将一个公用的find方法移入model类(比如本例中的查找所有未完成的任务),然后就可以在controller中多次重用,也包括通过表间关联来查找。
# tasks_controller.rb
def index
  @tasks = Task.find_incomplete
end

# models/task.rb
def self.find_incomplete
  find_all_by_complete(false, :order => 'created_at DESC')
end

# projects_controller.rb
def show
  @project = Project.find(params[:id])
  @tasks = @project.tasks.find_incomplete
end

你可能感兴趣的:(Ruby)