@task = Task.find( :all, :conditions=> [‘complete= ?’ ,false] )
with dynamic find_by_all
@task = Task.find_all_by_complete(false)
without dynamic find_by
@task = Task.find( :first, :conditions=> [‘complete= ?’ ,false],
:order=>’created_at DESC’ )
with dynamic find_by
@task = Task.find_by_complete(false, :order=>’created_at DESC’)
find by id
find( params[:id], :conditions=>[“name=?”, “peter” ] )
find through association
ex:
project has many tasks
task belongs to project
without association:
@task = Task.find(:all, :conditions=> [ ‘proect_id=? AND complete =?’ , @project_id, false] )
with association:
@project = Project.find(params[:id])
@task = @project.tasks.find(:all, :conditions=>[‘complete=?’, false])
or
@task = @project.tasks.find_all_by_complete(false)
find method in model
將find method定義在model比較好
ex:
Task的model
def self.find_incompletet
find_all_by_complete(false, :order=>’created_at DESC’ )
end
注意: 此find method要定義成class method
到時候可呼叫 @project.tasks.find_incomplete
若定義成instance method,則會error
find_by_sql:
use sql syntax in the find_by_sql
pros: faster
沒有留言:
張貼留言