RailsCasts中文版,#2 Dynamic find_by Methods 使用动态的find_by方法进行查找操作

下面给大家演示一个Rails中使用Find方法更加优雅的方式。例子中Task类有一个属性complete表明任务是否已经完成(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

查找所有未完成的任务,可以将代码中下面的代码用find_by_all替换。

@tasks = Task.find(:all, :conditions => ['complete = ?', false])

其中complete是条件字段的名字。

@tasks = Task.find_all_by_complete(false)

如果想查找某一个Task,使用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参数。

作者授权: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/2-dynamic-find-by-methods

posted on 2012-11-18 22:15  边晓宇  阅读(950)  评论(0编辑  收藏  举报