[英]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 :( 目前我得到一个例外,因为它不是数字'NaN'...因为它是空的:(
As always - any help massively appreciated for a Rails beginner here..! 与往常一样-这里的Rails初学者非常感谢任何帮助..!
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: 假设
methodName
始终存在(作为一种方法),并且当该值存在时返回Numeric,否则返回nil
或false
:
@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. 这将导致所有没有条目的记录都在
reverse
之前在列表的开头,然后在列表的末尾。
If that doesn't work, please state what methodName
returns for the new records. 如果这不起作用,请说明为新记录返回的
methodName
。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.