开发者

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..!


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| %>


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜