Ruby on Rails數據表格關係

一對一關係實例: one-to-one
class Order < ActiveRecord::Base
has_one :paid_order,
    :class_name =>"Order",
    :foreign_key => "order_id",
    :conditions => "paid_on is not null"
在表格上加order_id (表格名單數_id)
class Invoice < ActiveRecord::Base
belongs_to :order

可選參數:class_name, :foreign_key,  :order, :conditions
:dependent => true #刪除主錶行時同時刪除子行
自定義的order用法:
class Customer < ActiveRecord::Base
has_many :orders
has_one :most_recent_order,
    :class_name => ‘Order’,
    :order => ‘created_at DESC’
end

主.從 將被保存
an_invoice = Invoice.new(…)
order.invoice = an_invoice # invoice被保存
從.主 將要手動保存

新增加的方法:
product(force_reload=false)
product=(obj)
build_product(attributes={})
create_product(attributes={})

一對多關係(one-to-many)
class Order < ActiveRecord::Base
has_many :line_items
可選參數除了上面的,還有:exclusively_dependent, :finder_sql,:counter_sql
:exclusively_dependent 在子行沒有其它表格瓜葛的情況下使用, 加快處理速度.
:finder_sql的使用實例:
class Order < ActiveRecord::Base
has_many :rails_line_items,
     :class_name => "LineItem",
     :finder_sql => "select l. * from line_items l, products p " +
     " where l.product_id = p.id " +
     " and p.title like ‘%rails%’"
end
order的用法:
class Order < ActiveRecord::Base
has_many :line_items,
   :order =>"quantity, unit_price DESC"
end

主.從 將被保存
an_invoice = Invoice.new(…)
order.invoices <<an_invoice # invoice

class LineItem < ActiveRecord::Base
belongs_to :order
. . .

has_many後可以引用集合:
order = Order.find(123)
total = 0.0
order.line_items.each do |li|
 total += li.quantity * li.unit_price
end

新增加的方法:
orders(force_reload=false)
orders <<order
orders.push(order1, …)
orders.delete(order1, …)
orders.clear
orders.find(options…)
orders.build(attributes={})
orders.create(attributes={})

多對多關係(many-to-many):
class Product < ActiveRecord::Base
has_and_belongs_to_many :categories
. . .
class Category < ActiveRecord::Base
has_and_belongs_to_many :products
. . .

要創建一個中間表格:
categories_products
兩表格名字複數形式相聯, 排字母前後排序

表格內連關聯鍵

預載子表
用:include將子表內容加入內存,提高查詢速度, 但損耗內存:
for post in Post.find(:all, :include => [:author, :comments])
 puts "Post: #{post.title}"
 puts "Written by: #{post.author.name}"
 puts "Last comment on: #{post.comments.first.created_on}"
end

自動計算子錶行數
 belongs_to加參數:counter_cache => true
 數據庫加 子表格名(複數)_count 段, 並加 :default=>0參數.
 然後用 .size可以讀取子錶行數.
刷新數據讀法:product.line_items(:refresh).size

此條目發表在 Ruby on Rails 分類目錄。將固定鏈接加入收藏夾。

Ruby on Rails數據表格關係》有 2 條評論

  1. flying.piggy.cn@gmail.com 說:

    很有幫助,謝謝。

  2. zmplsf2587970@126.com 說:

    very good!!

發表評論