Say for example I have an event with start_date
and length
(as integer representing days).
In the model I define end_date
as start_date + length.days
very simply as you would expect:
def end_date
start_date + length.days
end
All works fine in the template, I can use event.end_date
to display the start date plus however many days length was set to, however, I want to now order the events by the end date using Ransack.
The sort link for start_date
looks like this: <%= sort_link @q, :start_date, "Start" %>
If I try the same for end_date (<%= sort_link @q, :end_date, "End" %>
) it unfortunately silently fails as I presume it's looking for end_date
as a column in the table and not finding it.
Am I just being stupid or am I trying to do something Ransack simply wasn't made to do?
ransacker :end do |r|
in the model to this:Arel::Nodes::SqlLiteral.new("DATE_ADD(events.start_date, INTERVAL events.length DAY)")
. Which produces the query:SELECT DISTINCT events.* FROM events ORDER BY DATE_ADD(events.start_date, INTERVAL events.length DAY) DESC LIMIT 30 OFFSET 0
. That does work, but feels horribly 'hacky'. – Batt