Question

I'm using Ransack's sort_link in my rails project to display a list of fees for my payment model. However, 'fee_amount' isn't an attribute of the payment model, but instead a class method of the bill model (which belongs to payment). What I have currently is:

<%= sort_link @search, :bill_fee_amount, "Convenience Fee" %>

which should accesses the bill of the current payment and call the 'fee_amount' method on that bill, which does some calculations and returns a float. It's these floats that I'm hoping to search by.

Can this be done, or can I only sort by attributes of the model I'm dealing with?

Was it helpful?

Solution

Ransack is the successor to MetaSearch, and according to the MetaSearch documentation, you can create custom searches. Here's the link:

https://github.com/ernie/meta_search

I think something like this would work:

scope :sort_by_bill_fee_amount_asc, joins(:bill).select('sum("bills"."fee_amount") AS bill_fee_amount').order('bill_fee_amount ASC')
scope :sort_by_bill_fee_amount_desc, joins(:bill).select('sum("bills"."fee_amount") AS bill_fee_amount').order('bill_fee_amount DESC')

The question wasn't clear about what the calculation is exactly so I assumed it was just a sum of a field called fee_amount. Unfortunately, it's probably much worse than that and I think the nasty SQL calculation will need to be included in the Payment model.

The key point I think is that the SQL needs to include the column you are sorting on so you need to have the SQL calculate it and include it with the name that Ransack wants to search on.

I hope that helps.

OTHER TIPS

You can't with ransack as it comes, but check this issue. It seems some people has made patches for this functionality, but I haven't tried them.

Ransack, internally, it's always using the model as defined in the database, and I couldn't make it use the temporary tables created by the scopes.

PD: reworked the comment as an answer as I always come back to this question :P

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top