2009-04-29 44 views
3

我正在建立一個關鍵字緩存在表中的搜索。在表中查找用戶輸入的關鍵字之前,將其標準化。例如,一些標點符號(如' - ')被刪除,套管標準化。規範化的關鍵字然後用於查找搜索結果。實現一個ActiveRecord before_find

我目前正在使用before_filter處理控制器中的規範化。我想知道是否有辦法在模型中做到這一點。概念上像「before_find」回調的東西可以工作,儘管這對於實例級別沒有意義。

回答

2

你應該使用命名範圍:

class Whatever < ActiveRecord::Base 

    named_scope :search, lambda {|*keywords| 
    {:conditions => {:keyword => normalize_keywords(keywords)}}} 

    def self.normalize_keywords(keywords) 
    # Work your magic here 
    end 

end 

使用命名範圍將讓你與其他作用域鏈,是真正使用Rails 3

要走的路
0

你可能不想通過重寫find來實現這個。重寫發現之類的東西可能會成爲頭痛的問題。

您可以創建一個類的方法,做不過你需要什麼,是這樣的:

class MyTable < ActiveRecord::Base 
    def self.find_using_dirty_keywords(*args) 
    #Cleanup input 
    #Call to actual find 
    end 
end 

如果你真的想重載發現你可以這樣來做:

舉個例子:

class MyTable < ActiveRecord::Base 
    def self.find(*args) 
    #work your magic here 
    super(args,you,want,to,pass) 
    end 
end 

有關子類結賬更多信息此鏈接:Ruby Tips

0

非常喜歡上面的,你也可以用alias_method_chain

class YourModel < ActiveRecord::Base 

    class << self 
    def find_with_condition_cleansing(*args) 
     #modify your args 
     find_without_condition_cleansing(*args) 
    end 
    alias_method_chain :find, :condition_cleansing 
    end 

end