@tasks = Task.find(:all, :conditions => [ 'complete = ?', false ])
@task = Task.find(:first, :conditions => [ 'complete = ?', false ], :order => 'created_at DESC')
以动态的find_by和find_all_by方法缩短查询语句,以下代码等效。
@tasks = Task.find_all_by_complete(false)
@task = Task.find_by_complete(false, :order => 'created_at DESC')
另外
1.对于:conditons后面有2个参数的情况,下面的代码等效。
Task.find(:all, :conditions => [ 'complete = ? AND category_id = ?', false, 1 ])
Task.find_all_by_complete_and_category_id(false, 1)
2.动态查询支持nil, array以及range作为参数。看源代码有下面一段:
def attribute_condition(argument)
case argument
when nil then "IS ?"
when Array then "IN (?)"
when Range then "BETWEEN ? AND ?"
else "= ?"
end
end
于是,如果想要查询上海或者北京,18到30岁的用户,可以这么写
User.find_all_by_city_and_age([ 'Shanghai', 'Beijing' ], 18..30)
3.动态查询仍然可以使用:conditions参数,额外的条件会使用with_scope来约束。
Book.find_by_title('title', :conditions => ['price > ?', price])