find 是 ActiveRecord 查詢的核心,支援豐富選項構建複雜查詢。
:first / :allfind(:first, ...):回傳單一物件,相當於 LIMIT 1find(:all, ...):回傳陣列| 選項 | 說明 | 範例 |
|---|---|---|
:conditions | WHERE 條件,支援字串、陣列、Hash | :conditions => ["name = ?", "Dave"] |
:order | ORDER BY 子句 | :order => "pay_type, shipped_at DESC" |
:limit | 限制回傳筆數 | :limit => 10 |
:offset | 跳過筆數,配合 limit 分頁 | :offset => page_num * page_size |
:joins | JOIN 子句片段 | :joins => "inner join products ..." |
def self.find_on_page(page_num, page_size) find(:all, :order => "id", :limit => page_size, :offset => page_num * page_size) end
find_by_sqlorders = LineItem.find_by_sql( "select line_items.* from line_items, orders " + "where order_id = orders.id and orders.name = 'Dave Thomas'" )
回傳模型物件,屬性對應 SELECT 列表。可用 attributes、attribute_names、attribute_present? 檢查載入欄位。
items = LineItem.find_by_sql(
"select *, quantity*unit_price as total_price, products.title as title " +
"from line_items, products where line_items.product_id = products.id"
)
li = items[0]
puts "#{li.title}: #{li.quantity}x#{li.unit_price} => #{li.total_price}"
Order.find_by_sql(["select * from orders where amount > ?", params[:amount]])