通过使用动态的find_all_by和find_by方法提高代码的可读性。
Rails中的find方法非常有用,下面是一个Task模型,定义了两个方法分别寻找所有未完成的task和最后一个未完成的task
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
使用find_all_by和find_by同样可以达到目的,并且提高了代码的可读性。
将
@tasks = Task.find(:all, :conditions => ['complete = ?', false])
替换为
@tasks = Task.find_all_by_complete(false)
如果需要查找最后一条记录(按时间排序),则使用find_by_complete
将
@task = Task.find(:first, :conditions => ['complete =?', false], :order => 'created_at DESC')
替换为
@task = Task.find_by_complete(false, :order => 'created_at DESC')
find_by使用order参数的方法与find相同。
在项目中试了下:
Irm::People.find_by_first_name("Ironmine")
生成的sql为
SELECT `irm_people`.* FROM `irm_people` WHERE `irm_people`.`first_name` = 'Ironmine' LIMIT 1
Irm::People.find_all_by_first_name("Ironmine")
生成的sql为
SELECT `irm_people`.* FROM `irm_people` WHERE `irm_people`.`first_name` = 'Ironmine'
Irm::People.find_all_by_first_name("Ironmine",:order => 'created_at DESC')
生成的sql为
SELECT `irm_people`.* FROM `irm_people` WHERE `irm_people`.`first_name` = 'Ironmine' ORDER BY created_at DESC
注:
动态finder方法在Rails4.0中已经不赞成使用,在Rails4.1中将被废除,应该使用Active Record scope替换动态finder。
原文链接:http://railscasts.com/episodes/2-dynamic-find-by-methods?view=asciicast