2009-05-17 40 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, ...)