2009-05-17 63 views

回答

1

我碰到它搜索出來。 searchlogic是完美的。

1

因爲您正在處理來自用戶的數據,所以我會遠離eval。也許只是使用一個簡單的案例陳述?這樣你就可以驗證他們給你的數據。

2

我會建議我非常棒的acts_as_filter插件,用於通過named_scopes對結果進行用戶驅動的過濾。

http://github.com/tobyhede/acts_as_filter/tree/master

評估和演示是蠻好用的 - (?我往往只是塞一些值到一個數組,測試accepted_values.include(參數)),但請務必驗證對接受/預期值

2

EVAL是一個非常糟糕的主意。然而,#send對此非常完美 - 它本質上更安全,並且比eval更快(據我瞭解)。

Product.send(params[:scope]) 

應該這樣做:)

0

對於你給的例子,我是明確的,和連鎖範圍,共同打造你想要的查詢:

scope = Post 
scope = scope.random if params[:scope] == 'random' 
@posts = scope.find(:all, ...) # or paginate or whatever you need to do 

如果PARAMS [ :範圍]不是'隨機',這是相同的調用Post.find(),否則它正在做Post.random.find()

從其他答案之一,它看起來像find_by_filter會做漂亮很薄g給你。

如果您需要支持非互斥的東西,例如使用此模式,還可以將多個範圍組合到查詢中。 ?

scope = scope.only_monsters if params[:just_monsters] == 1  
scope = scope.limit(params[:limit].to_i) unless params[:limit].to_i.zero? 

因此讓/職位範圍=隨機& just_monsters = 1門&限值爲5會給你:

Post.random.just_monsters.limit(5).find(:all, ...)