5

I'm working on a rails 3.2 ruby 1.9.2 project.

I get some values from database with a classic:

designators = Model.find()

And I show it in view with (simplified code):

<table class="rwy_modes_table" cellspacing='0'>
  <% designators.each do |info_design| %>
    <tr id="rwy_mode_<%=info_design.id%>">
      <td class="spacer"><%= info_design.try(:designator) %></td>
    </tr>
  <% end %>
</table>

Values are for example: 3L, 3C, 3R. (L for Left, C for Center, 4 for Right). I would like values ordered such as: 3L, 3C, 3R and not 3C, 3L, 3R

I don't know how to define this custom order. Any idea ?

1
  • What is 3 ? Can you show the view code? Commented Aug 25, 2014 at 10:57

2 Answers 2

6

Try something like this:

(app/models/designator.rb)
# determines the sort value for based on my_attribute.
# designators should be in the order 'l', 'c', 'r' - regardless of any preceeding numeral
def sort_val
  return 0 if self.my_attribute =~ /l/i
  return 1 if self.my_attribute =~ /c/i
  return 2 if self.my_attribute =~ /r/i
end

(app/helpers/designators_helper.rb)
def sorted_designators(designators)
  designators.sort{|a, b| a.sort_val <=> b.sort_val }
end

Where you can do sorting in your view

(app/views/...)
sorted_designators(designators).each do |design|

Alternately, you can move this to a static method in your model file, for easy sorting outside your view

(app/models/designator.rb)
def self.sorted_designators(designators)
  designators.sort{|a, b| a.sort_val <=> b.sort_val }
end

and use them in your controller like this

app/controllers...
@designators = Designator.sorted_designators(designators)

Note: this is an in-memory sort, so watch for O(n) db queries depending on how you sort / access this object

See also: https://stackoverflow.com/a/14282353/811255 for using the Comparable module (probably a cleaner solution)

Sign up to request clarification or add additional context in comments.

Comments

3

You could do something like this. This is not a complete answer, but this approach might help.

arr = ["3R", "3C", "2C", "4C", "2L", "2R", "3L", "4R", "4L"] # Array to be sorted

tmp_arr = ['L', 'C', 'R']

arr.sort_by {|s| [s[0], tmp_arr.index(s[1])] }
# => ["2L", "2C", "2R", "3L", "3C", "3R", "4L", "4C", "4R"]

This assumes "2R" comes before "3L", If you want to ignore numbers while sorting, you can remove s[0] from the code block

1 Comment

Your approach helps. I edit my answer to be more clear. Your solution works for ruby array. In my case it's an active record association.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.