下面给大家演示一个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

相关文章:

  • 2021-11-28
  • 2022-12-23
  • 2021-12-01
  • 2021-06-12
  • 2021-08-05
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-11-30
  • 2022-12-23
相关资源
相似解决方案