ActiveRecord 讓建立記錄如同操作普通 Ruby 物件,支援多種建構與儲存方式。
new + savean_order = Order.new an_order.name = "Dave Thomas" an_order.email = "dave@pragprog.com" an_order.address = "123 Main St" an_order.pay_type = "check" an_order.save
Order.new do |o| o.name = "Dave Thomas" # ... o.save end
an_order = Order.new( :name => "Dave Thomas", :email => "dave@pragprog.com", :address => "123 Main St", :pay_type => "check" ) an_order.save
遵循慣例(整數 id 主鍵 + 自增),save 後自動回填 id:
an_order.save
puts "The ID of this order is #{an_order.id}"
createan_order = Order.create( :name => "Dave Thomas", :email => "dave@pragprog.com", :address => "123 Main St", :pay_type => "check" )
orders = Order.create([
{:name => "Dave Thomas", :email => "dave@pragprog.com", ...},
{:name => "Andy Hunt", :email => "andy@pragprog.com", ...}
])
回傳已儲存模型陣列。Controller 中常直接以 Order.create(params) 接收表單資料。