Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Manual sorting in ActiveRecord

Each company in my database has many projects, and every company is given a 'General tasks' project when they sign up. This particular project cannot be deleted by its company, and it is treated as a special repository for tasks that have not yet been assigned to one of the company's other projects.

When displaying the company's projects, I want them to appear in alphabetical order but with the single exception that 'General tasks' appears at the top. This requires some kind of special handling of the project for sorting purposes. How can I take:

@projects = @company.projects

and sort it so we get a list like this:

'General tasks'
'ABC Project'
'BFA Project'
'ZNS Project'
like image 934
sscirrus Avatar asked Aug 11 '26 12:08

sscirrus


1 Answers

You can do this in SQL. Here is an example that works in PostgreSQL. Couldn't figure out how to make a database-agnostic version, but you should be able to tailor it to your RDBMS.

@projects = @company.projects.order("name != 'General tasks', name")

!= returns a boolean value, and in PostgreSQL false comes before true so we need NOT EQUAL to make sure the records with the name "General tasks" are shown first. Remaining projects will be sorted by their name.

Another approach would be to add a column to your projects table which flags the "General tasks" projects as special, like:

add_column :projects, :permanent, :boolean, :default => false

Then, you can sort without using raw SQL:

@projects = @company.projects.order(:permanent, :name)
like image 93
Carl Zulauf Avatar answered Aug 13 '26 07:08

Carl Zulauf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!