RailsCasts中文版,#4 Move Find into Model 将查询方法从控制器上移至模型
这个例子是对Task
调用find
命令进行查询操作,查询所有未完成的任务并按照创建时间降序排列。如下所示:
class TaskController < ApplicationController def index @tasks = Task.find_all_by_complete(:false, :order => "created_at DESC") endend
@tasks = Task.find_incomplete
.self
class Task < ActiveRecord::Base belongs_to :project def self.find_incomplete find_all_by_complete(:false, :order => "created_at DESC") endend
Task
了,因为查找的作用域在类内部。增加了方法后,我们就可以调用封装后的Task.find_incomplete
方法代替之前的写法。甚至在级联查询的时候依然生效,比如查询在Project
下的所有未完成任务:class ProjectsController < ApplicationController def show @project = Project.find(params[:id]) @tasks = @project.tasks.find_incomplete endend
作者授权:You are welcome to post the translated text on your blog as well if the episode is free(not Pro). I just ask that you post a link back to the original episode on railscasts.com.
原文链接:http://railscasts.com/episodes/4-move-find-into-model