ubuntu, ror, jQuery, css, website memo
太嫩, 沒啥心得, 用來紀錄每天學的
2009年3月10日 星期二
ActiveRecord memo(2)
1. 18.1 p379
#會建立一個可同時在兩個外鍵欄位上搜尋的index, 一般而言便是可以很快找到某個 product_id 所對應的category_id
add_index :categories_products, [:product_id, :category_id]
#再利用這個index 快速取得此category
add_index :categories_products, :category_id
2. 18.3 p384
>> u = User.first
=> #
>> u.profile.others
=> "dddddddddd"
>> u.profile.others
=> "dddddddddd"
>> u.profile.others
=> "dddddddddd"
#傳回的profile object 結果被cache 了, 所以只撈了一次db
User Load (0.2ms) SELECT * FROM `users` LIMIT 1
Profile Load (0.6ms) SELECT * FROM `profiles` WHERE (`profiles`.user_id = 1) LIMIT 1
3. dependent
#砍上面的, 下面的也砍
:dependent => :destroy(or true)
#砍上面的, 下面設成foreign key 設成null
:dependent => :nullify
#砍上面的不理下面的
:dependent => :false(or nil)
4 18.3 p389, :finder_sql, and order
#select A的東西, 卻需要B的條件時
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%'"
#這樣是先照quantity 的ASC 做排序, 相同時再用unit_price DESC 排序
has_many :line_items, :order => "quantity, unit_price DESC"
5. 18.3 p391 has_many 的一些method, <<, push, replace, clear, uniq(好像拿掉了)
6. 去除重覆的部份
sql distinct
#unique的動作是在ActiveRecord 做的
has_many :users, :through => :readings, :unique => true
#可以在sql 做好
has_many :users, :through => :readings, :select => "distinct users.*"
7. has_many, extend
#基本
#原本
class Organization < ActiveRecord::Base
has_many :people do
def find_active
find(:all, :conditions => ["active = ?", true])
end
end
end
#弄到自己的module
module FindActiveExtension
def find_active
find(:all, :conditions => ["active = ?", true])
end
end
class Organization < ActiveRecord::Base
has_many :people, :extend => FindActiveExtension
end
#-----------------------------------------------------------
#高級技巧 XD
#原本的樣子
class Project < ActiveRecord::Base
has_many :tasks, :dependent => :delete_all do
def active(reload=false)
@active = nil if reload
@active ||= find(:all, :conditions => "status = 'active'")
end
def inactive(reload=false)
@inactive = nil if reload
@inactive ||= find(:all, :conditions => "status = 'inactive'")
end
end
end
#利用 extend 的技巧
class Project < ActiveRecord::Base
has_many :tasks, :dependent => :delete_all do
memoized_finder :active, "status = 'active'"
memoized_finder :inactive, "status = 'inactive'"
end
end
#注意他是弄在core module
class Module
def memoized_finder(name, conditions=nil)
class_eval <<-STR
def #{name}(reload=false)
@#{name} = nil if reload
@#{name} ||= find(:all, :conditions => #{conditions.inspect})
end
STR
end
end
沒有留言:
張貼留言
較新的文章
較舊的文章
首頁
訂閱:
張貼留言 (Atom)
沒有留言:
張貼留言