Sort_By with Boolean in Rails

sort_by with Boolean in Rails

You could cheat and get it to return a number:

sort_by { |a| a.thing ? 0 : 1 }

Ruby sort by boolean and number

This does the job:

array.sort{|a,b| (a[:accepts] == b[:accepts]) ? ((a[:id] < b[:id]) ? -1 : 1) : (a[:accepts] ? -1 : 1)}

Ruby on Rails - Order records by created_at and sort_by by boolean

Max's answer is the way to go, the only thing missing in his comment was wrapping it in Arel.sql

posts = Post.active.order(Arel.sql("CASE WHEN pinned THEN 0 ELSE 1 END"), "created_at DESC"))

Rails: Sorting and Filting Data based on boolean attribute

You could structure your params as a hash, and pass it to conditions:

# example:
params = {
:filters => {
:active => true,
:name => 'Boby',
# etc...
}
}

filters = params[:filters]
@projects = Project.where(filters)

Sort Objects by Boolean values in Ruby

Most languages provide sort functions that accept comparators for this sort of thing. In Ruby, this is just array.sort:

p.sort {|a, b| if (a.preferred_provider? == b.preferred_provider?
then a.price <=> b.price
elsif a.preferred_provider?
1
else -1
}

Sorting scope by boolean values (rails model)

In the index controller

@pins = Pin.featured_order 

Then you can iterate over it.
This will sort by featured order and resort to default_scope if needed.

If this doesn't work, you're best bet would be to create to scopes and use the as needed instead of default scope.

I always err on the side of using default scope.

Lightweight method to order on boolean attribute in true/false/nil order

Found the answer:

Foo.order("bar DESC NULLS LAST").map{|f| f.bar}.uniq
=> [true, false, nil]
Foo.order("bar DESC NULLS LAST").class
=> Foo::ActiveRecord_Relation

a boolean parameter OR string parameter for allowing a caller to set the sort order of a result set

One other option is to use a sortBy parameter and allow values like +firstName or -firstName to indicate the column AND direction. This could then allow you to expand the API to allow for multi column sorting. i.e. api/employees?sortBy=-age,+salary. Finally sort order is also important when considering pagination. It seems to make sense to be consistent in the GET request for both



Related Topics



Leave a reply



Submit