0

Is it legit to call something like User.order() if I have situation where I might have to pass some parameters but if they do not exist I need default order. Or is there some default call..

So for example

# if the order_by exists I need to sort by that otherwise I need to get default results
order = params[:order_by]
@results = User.order(order)
CodeCrack
  • 5,253
  • 11
  • 44
  • 72

1 Answers1

1

If you don't know which params will you receive, you can try to use following code:

@users = User.scoped # or any other default handler which returns ActiveRecord::Relation
@users = @users.where(name: params[:name]) if params[:name].present?
@users = @users.order(params[:order_by]) if params[:order_by].present?
Rustam Gasanov
  • 15,290
  • 8
  • 59
  • 72
  • Awesome! So User.scoped just returns default query? The docs on .scoped are not that clear. – CodeCrack Nov 29 '14 at 20:13
  • It returns results of a query to specified table without any restrictions(of course when you fire it, just `User.scoped` code will not fetch anything, it will just return `ActiveRecord::Relation`, which you can modify according to your needs). You can read detailed explanation here: [Scoped and scope in rails](http://stackoverflow.com/a/11902011) – Rustam Gasanov Nov 29 '14 at 20:18
  • That seems not to work with my code. Check out my other thread with code http://stackoverflow.com/questions/27207436/how-can-i-order-data-based-on-if-a-param-has-been-set-or-not – CodeCrack Nov 29 '14 at 22:04
  • @CodeCrack you can't chain after `.all` or `.find` since these methods fire db query, in contrary to `.scoped`, which creates `AR::Relation`. And you have a typo `.scope` instead of `.scoped`. Leantraxxx gave you correct answer – Rustam Gasanov Nov 30 '14 at 00:04