replacing certain column values with "-" in a will_paginate result set without affecting sorting
I have a model table with 3 fields: "id", "amount" and "type". Im calling the paginate method to display the data but I need to replace the amount with "-" if type = "specific_type".
I can do this by replacing the values in the view with a "-" if the type condition is met. But this screws up the sort order as I would like the "-"开发者_开发问答 values to be effectively evaluated as 0 but replacing values only in the view still leaves me with an incorrect sort order.
I thought about using find_by_sql and trying to create a virtual field using a CASE statement
select *, CASE type WHEN 'specific' THEN amount ELSE '-' END from amounts;
this way, I can use the virtual column.
The problem is that I need to take in a param hash of options which I would then have to manually render to SQL where clause. This sounds tedious unless there's a better way of doing it.
In your controller:
def index
@resources = []
your_resources = Resource.find(:all)
your_resources.each do |resource|
resource.amount = '-' if resource.amount = "specific_type"
@resources << resource
end
end
I'd try to implement an attribute reader in your model like:
class YourModel < ActiveRecord::Base
def amount
(self.type == "specific_type") ? "-" : read_attribute(:amount)
end
end
精彩评论