Jamie
Jamie

Reputation: 1014

Rails sort_by method if value is not empty

So I've got a method that I'm using to sort by the result instead of a database column at the moment which works nicely. It will return from the below each loop with a value against each record, then sort the table based on these:

<% @records.sort_by(&:methodName).reverse.each do |record| %>
    <%= record.methodName %>
<% end %>

This works really well - however this method only gets used after a user interacts with the record itself. For instance like a rating, so a record will begin life without a rating, then ratings will be submitted after this point.

It works nicely, until you create a new record that doesn't have a value for this to sort by - is there a way of saying "Sort by what this method returns, if the record doesn't have a value for this, put it at the bottom"?

At the moment I get an exception because it's not a number 'NaN'...because it's empty :(

As always - any help massively appreciated for a Rails beginner here..!

Upvotes: 1

Views: 2647

Answers (2)

Phrogz
Phrogz

Reputation: 303251

Assuming that methodName always exists (as a method) and returns a Numeric when the value exists and nil or false otherwise:

@records.sort_by{ |r| r.methodName || -9999999 }

That will cause all records with no entry to be at the start of the list before the reverse, and at the end of the list afterwards.

If that doesn't work, please state what methodName returns for the new records.

Alternatively, you could do this:

newrs, oldrs = @records.partition{ |r| r.methodName }
newrs.each do |r| ... records that have a value for methodName ... end
oldrs.each do |r| ... records with no value for methodName ... end

Upvotes: 3

Dogbert
Dogbert

Reputation: 222198

Try this

<% @records.sort_by{|r| r.try(:methodName)}.reverse.each do |record| %>

Edit:

<% @records.sort_by{|r| r.methodName.nan? ? 10000 : r.methodName}.reverse.each do |record| %>

Upvotes: 3

Related Questions