`
Hooopo
  • 浏览: 336069 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Move Find Into Model

阅读更多
下面是在控制器里面通过model查找未完成的任务:

class TaskController < ApplicationController  
  def index  
    @tasks = Task.find_all_by_complete_(false, :order => "created_at DESC")  
  end  
end  

If the find is being performed several times throughout the application then there will be duplication. One way to remove this duplication is to move the find into the model, which would allow us to call
@tasks = Task.find_incomplete  

in the controller. To do this we’ll need to create a new method in the model. The method has to be a class method so must start with self.
class Task < ActiveRecord::Base  
  belongs_to :project  
  
  def self.find_incomplete  
    find_all_by_complete_(false, :order => "created_at DESC")  
  end  
end  

There’s no need to specify Task in the find line as the find is already scoped inside the Task class. Now you can call Task.find_incomplete whenever you need to perform that find. This will even work in associations so that you can find Project’s incomplete tasks like this:
class ProjectsController < ApplicationController  
    def show  
        @project = Project.find(params[:id])  
        @tasks = @project.tasks.find_incomplete  
    end  
end  

分享到:
评论
1 楼 qichunren 2009-08-05  
Hooopo转帖子为什么不写地址?我要看原帖子,哇哇啦~~·

相关推荐

Global site tag (gtag.js) - Google Analytics