2017-03-17 85 views
0

find_by_ *可能是其怪異的一些人有關的問題。通過查看其可識別的語法類別類別方法它是如何工作的軌道

Model.find_by_* 

因此,如果其類的方法應該被定義或者在模型我們創建或

ActiveRecord::Base 

所以我的問題是軌如何管理添加這些方法,讓我們使用。

實例像

Model.find_by_id 
Model.find_by_name 
Model.find_by_status 

回答

2

你需要看看ActiveRecord::FinderMethodsHere你可以找到更多的細節。

在內部,它觸發基於存在於find_by_attributes屬性的WHERE查詢。它返回第一個匹配的對象。

def find_by_attributes(match, attributes, *args) 
    conditions = Hash[attributes.map {|a| [a, args[attributes.index(a)]]}] 
    result = where(conditions).send(match.finder) 

    if match.bang? && result.nil? 
    raise RecordNotFound, "Couldn't find #{@klass.name} with #{conditions.to_a.collect {|p| p.join(' = ')}.join(', ')}" 
    else 
    yield(result) if block_given? 
    result 
    end 
end 

還有find_all_by_attributes返回所有匹配的記錄。

1

導軌使用紅寶石元編程method_missing爲該。該方法find_by_name不是一個模式,而不是這個軌道正在name作爲第一個參數,它調用它像find_by(name: ?)這是調用where(name: ?).take

+0

謝謝你,我很感激,我知道的method_missing。 –