开发者

Sorting by calculated value with Rails

I am currently sorting a data table in a Rails 2.3 application by various different columns using the sortable_column_headers plugin. This works great and I can sort columns on the current model or easily on associated models too.

My problem though is one column in the table is a calculated value (it's the result of divising one column by another) and I now need to make it possible to sort by 开发者_Python百科this calculated column data. The calculation is done when the table is displayed as follows:

<td><%= market_cr(employee.salary_annual,employee.payscale.market_midpoint) %></td>

And market_cr is:

def market_cr(current_salary,market_mp)
number_to_percentage((current_salary/market_mp)*100, :precision => 1)

end

How can I make this column sortable the way I have done with others, e.g:

<th><%= link_to 'Market CR', sort_param('listing', :model => Employee, :field => 'market_cr'), :id => 'market_cr' %></th>

Thanks!


I'm not familiar with sortable_column_headers, but it seems like this could be accomplished by moving the market_cr method from a view helper to the employee model. Something like this, but you might need to massage it a little more in the view to get it to look like a percentage. This is probably a better solution if you are doing unit testing too.

class Employee < ActiveRecord::Base
  ....

  def market_cr
   ((salary_annual/payscale.market_midpoint)*100).round(1)
  end

  ....
end
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜