Move Find into Model 将查询方法从控制器上移至模型

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

这段代码的意思是查询所有未完成的任务并按照创建的时间先后排序。如果控制器中有好多个地方要用到,那么我们可以将这个方法抽出来放到模型中,用到的时候
@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")
  end
end




原文地址:https://www.cnblogs.com/JackyKun/p/4870583.html