2012-01-22 46 views
0

我有一個模型,有一個手機截取find_by_attribute方法活動記錄

手機存儲在數據庫中使用特定的格式。 我想攔截User.find_by_cellphone(「1234567890」)並正常化手機,然後調用「真正的」find_by_cellphone(「123-456-7890」)。

我該怎麼辦?我正在考慮將find_by_cellphone重命名爲ar_find_by_cellphone,然後覆蓋find_by_cellphone並在其中調用ar_find_by_cellphone。任何其他想法?

回答

1

實際上並沒有一個名爲find_by_cellphone的方法,這只是ActiveRecord神奇地使用Ruby的method_missing來動態地爲你做這個。

做你想做的,只是在你的Cellphone類中定義find_by_cellphone爲一個類的方法是什麼,它會用這個,而不是內置的一個:

def self.find_by_cellphone(number) 
    normalized_number = ... # normalize your number 
    self.where(:cellphone => normalized_number).first 
end 
+0

該死右擊這就是爲什麼我alias_method_chain不工作, 謝謝! – daniel

+0

雖然find_by_cellphone => self.where(...),但第一個 – daniel

+0

糟糕,錯過了這一點。更新。 –