2017-06-16 64 views
0

是否有可能在軌道上的紅寶石做這樣的事情?Rails中的動態範圍映射?

def method(scope: 'all') # so that it would use Model.all by default 
    Model.scope 
end 

method(scope: 'last(10)') # to get it to call Model.last(10) 

更新:爲了清楚起見,這並沒有特別涉及到在導軌scope類方法。我最初應該避免在使用「範圍」這個術語時避免混淆。請隨意將其視爲model_method。儘管如此,將會留下這個問題,以保留歷史作爲解決問題的答案之一。

+0

你已經有'Model.all'和'Model.last(10)'in rails –

+0

你的問題到底是什麼,這很令人困惑 –

+0

我希望它動態調用'Model.all'或'Model.last(10) '或'Model.some_other_method',根據我設置的'scope'。 – Magne

回答

2

可以在模型本身定義各自的範圍,有和沒有的參數來處理..

scope :scoping, ->(method = 'all') { send(method) } 
scope :scoping_with_arg, ->(method = 'limit', arg = 1) { send(method, arg) } 

然後,

Model.scoping('first') 
Model.scoping_with_arg('last', 10) 
+0

謝謝,我知道,但我想確定在運行時動態調用的實際範圍。 – Magne

+0

請不要告訴我你是從瀏覽器發送範圍。 – radubogdan

+0

@Magne請在運行時動態解釋*,我認爲它本身很漂亮*動態*本身 –

0

我發現瞭如何通過使用Ruby的#sendkeyword arguments,和使用數組來支持不止一個參數的模型示波器:

def method(scope: 'all', scope_args: []) # so that the method would call Model.all by default 
    Model.send(scope, *scope_args) 
end 

method(scope: 'last', scope_args: [10]) # to get it to call Model.last(10) 
method(scope: 'where', scope_args: [attribute: 'something']) # to get the method to call Model.where(attribute: 'something') 
+0

準確地說,你不能只有一個字符串來將其全部範圍,需要單獨傳遞參數.. –

+0

那麼,你可以,但是你必須用正則表達式解析字符串以從括號中提取參數。這似乎不值得僅僅爲了避免第二個參數。感謝提供第二個參數給'#send'的提示,這很有幫助! – Magne

+0

我已經嘗試過了,但並未涵蓋所有案例/可鏈接範圍,這就是我要求您列出清單的原因。 –