Allow user to select named object using GET parameters

In my message model, I have a named area:

named_scope :random, :order => "Random()"

      

I want to give users the ability to receive messages in no particular order by sending a GET request with params[:scope] = 'random'

.

Ends eval("Post.#{params[:scope]}")

how can I do this?

0


a source to share


5 answers


I found it in a search. searchlogic is perfect for this.



+1


a source


I would suggest my very awesome act_as_filter plugin designed to filter the results with a user using named_scopes.

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



Eval is great to use - but make sure you check for accepted / expected values ​​(do I often just plug some values ​​into an array and check accept_values.include? (Parameter))

+2


a source


eval is a pretty bad idea. However, #send is perfect for this - it is inherently safer and faster than eval (as I understand it).

Product.send(params[:scope])

      

This should do it :)

+2


a source


I would stay away from eval as you are dealing with data that comes from the user. Maybe just use a simple argument? This way, you can check what data they provide you with.

+1


a source


In the example you give, I would be explicit and concatenate the scopes to create the requested request:

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

      

If params [: scope] is not "random" this is the same as calling Post.find (), otherwise it does Post.random.find ()

From one of the other answers, it looks like find_by_filter will do the same for you.

Using this pattern, you can also combine multiple scopes into a query if you need to support things that weren't mutually exclusive for example

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

      

So GETting / posts? scope = random & just_monsters = 1 & limit = 5 will give you:

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

      

0


a source







All Articles