Custom Sort - Possible?

Hi all,

I’m working on a help system that lets users assign a “tag color” to
their requests in addition to assigning the usual “high, medium, low”
priority. My question is whether it’s possible to do a sort based on
the tag color. Valid colors are green, yellow, orange, and red, and
these are stored as strings in the database.

I’d like to use something like:

Customer Model

has_many :requests, :order => priority, tag_color

Is it possible to add a sort based on these string values?

Thanks!

I’m working on a help system that lets users assign a “tag color” to
their requests in addition to assigning the usual “high, medium, low”
priority. My question is whether it’s possible to do a sort based on
the tag color. Valid colors are green, yellow, orange, and red, and
these are stored as strings in the database.

I’d like to use something like:

Customer Model

has_many :requests, :order => priority, tag_color

That will sort them alphabetically, probably not what you want.

If there is an order those colors you could do something like this:

:order => “priority, tag_color = ‘red’, tag_color = ‘orange’,
tag_color = ‘yellow’, tag_color = ‘green’”

With an optional “DESC” thrown in to each of those. Basically that
converts your order by clause into a series of booleans and sorts that
way. Little ugly, but it will work.

-philip

You could also put a method like this in your Request model

def Request.sql_tag_color_order
‘(CASE requests.tag_color WHEN ‘red’ THEN 1 WHEN ‘yellow’ THEN 2
WHEN ‘green’ THEN 3 ELSE 4 END)’
end

Then change the line in your Customer model to
has_many :requests, :order => “priority,
#{Request.sql_tag_color_order}”

That way when you want to order requests in another part of your
application you can use Request.sql_tag_color_order instead of having
to repeat the transformation from text to something order.

HTH

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs