homeASCIIcasts

2: Dynamic find_by Methods 

(view original Railscast)

Other translations: It Fr Es Kr Pl Pt

This is a really useful way to do a Find in Rails. Below is a Task model that searches for tasks that haven’t been completed (i.e. the complete column is false).

  1. class TaskController < ApplicationController  
  2.     def incomplete  
  3.         @tasks = Task.find(:all:conditions => ['complete = ?'false])  
  4.     end  
  5.     def last_incomplete   
  6.         @task = Task.find(:first:conditions => ['complete =?'false], :order => 'created_at DESC')  
  7.     end  
  8. end  

There is a better way to achieve this with find_by_all. Just replace

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

with

  1. @tasks = Task.find_all_by_complete(false)  

If you just want to find one Task then use find_by, so to find the latest incomplete task the line

  1. @task = Task.find(:first:conditions => ['complete =?'false], :order => 'created_at DESC')  

becomes

  1. @task = Task.find_by_complete(false:order => 'created_at DESC')  

The find_by method takes the order parameter just like the find method does.