Rails & Ransack - Sorting/searching based on a definition in the model

Deadly 提交于 2019-11-30 10:08:05

Just for the benefit of anyone wanting to see how I did it:

In the model where I defined end_date

def end_date
  start_date + length.days
end

I then added a 'ranksacker' method for :end_date

ransacker :end_date do |r|
   Arel::Nodes::SqlLiteral.new("DATE_ADD(`events`.`start_date`, INTERVAL `events`.`length` DAY)")
end

I honestly don't know if this is the best/right way to do the above clause, but I'm far more familiar with SQL than with Ruby/Rails so it worked for me being so open.

What that effectively does is create a piece of SQL that orders a query by the same definition as end_date (start_date + length)

I can now in the template use the following code for a sort link (which allows Ransacker to handle the ASC/DESC and not interfere with wil_paginate etc etc):

<%= sort_link @q, :end_date, "Event End Date" %>

When you click that link you'll get a query along the lines of:

SELECT DISTINCT events.* FROM events ORDER BY DATE_ADD(events.start_date, INTERVAL events.length DAY) DESC LIMIT 30 OFFSET 0 - All created and handled by Ransacker on a column in your table that doesn't even exist!

Again, a quick disclaimer, I've been learning Rails and Ruby for about 2 weeks now, coming from a background of PHP so I am in NO WAY an expert and this could be horribly inefficient or there could be a much better 'rails way' that I simply do not know about.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!