首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Ruby on Rails 開發實戰(四十七):ActiveRecord 基礎 - 強大的 find 方法

     編輯:Java 相關知識

find 是 ActiveRecord 查詢的核心,支援豐富選項構建複雜查詢。

基本參數::first / :all

  • find(:first, ...):回傳單一物件,相當於 LIMIT 1
  • find(:all, ...):回傳陣列

常用選項

選項說明範例
:conditionsWHERE 條件,支援字串、陣列、Hash:conditions => ["name = ?", "Dave"]
:orderORDER BY 子句:order => "pay_type, shipped_at DESC"
:limit限制回傳筆數:limit => 10
:offset跳過筆數,配合 limit 分頁:offset => page_num * page_size
:joinsJOIN 子句片段: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

完整 SQL 控制:find_by_sql

orders = 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]])
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved