Home > Back-end >  rails one liner active records depends on params
rails one liner active records depends on params

Time:01-29

what I want to query is somethinkg like

Model.where(condition: params[:condition]) if params[:condition] exists.

otherwise its okay to return all.

I came up with one liner like Model.where(condition: params[:condition] || 0..Float::INFINITY)

but it didn't work.

Model.where(condition: 0..Float::INFINITY) works as I expected, so I thought above also would work.

Do you guys have any good idea to query by oneliner? I know ternary operator should work.

CodePudding user response:

params[:condition] || (0..Float::INFINITY) will only return (0..Float::INFINITY) in the case that params[:condition] is nil or false:

{ condition: "" }[:condition] || (0..Float::INFINITY)
# => ""
{ condition: false }[:condition] || (0..Float::INFINITY)
# => 0..Infinity
{ condition: nil }[:condition] || (0..Float::INFINITY)
# => 0..Infinity

You could use Object#presence to check if the value is not false, is empty, or a whitespace string:

{ condition: "" }[:condition].presence || (0..Float::INFINITY)
=> 0..Infinity

CodePudding user response:

otherwise its okay to return all

As I understand you need different scopes depend on condition

You can use chaining in that case

For example

models = Model.all
models = models.where(condition: params[:condition]) if params[:condition]

So if params[:condition] is truthy: some where scope will be used

If not: all records will be used

It's not one liner. But quite convenient

  •  Tags:  
  • Related