RailsCasts Pro episodes are now free!
Learn more or hide this
下面给大家演示一个在Rails中更加优雅地使用find方法进行数据查询的方式。例子中Task类有一个属性complete表明任务是否已经完成(complete字段是false意味着未完成),incomplete和last_incomplete方法分别用来返回所有未完成的和最后一个未完成的任务。
find
Task
complete
false
incomplete
last_incomplete
class TaskController < ApplicationController def incomplete @tasks = Task.find(:all, :conditions => ['complete = ?', false]) end def last_incomplete @task = Task.find(:first, :conditions => ['complete =?', false], :order => 'created_at DESC') end end
更好的方式是将这句代码
@tasks = Task.find(:all, :conditions => ['complete = ?', false])
用这句来替换
@tasks = Task.find_all_by_complete(false)
如果想查找某一个Task,使用find_by。比如,查找最后一个未完成的任务将last_incomplete方法中的这句代码
find_by
@task = Task.find(:first, :conditions => ['complete =?', false], :order => 'created_at DESC')
改为
@task = Task.find_by_complete(false, :order => 'created_at DESC')
find_by方法可以像find方法样接受order参数。
order