Rails & Ransack - Sort / search based on a definition in a model

Say, for example, I have an event with start_date and length (as an integer representing days).

In the model, I define end_date as start_date + length.days very simple, as you expected:

 def end_date start_date + length.days end 

Everything works fine in the template, I can use event.end_date to display the start date plus no matter how long the length is set, however . I want to now streamline events to an end date using Ransack.

The sort link for start_date as follows: <%= sort_link @q, :start_date, "Start" %>

If I try to do the same for end_date ( <%= sort_link @q, :end_date, "End" %> ), it unfortunately fails, as I assume that it searches for end_date as a column in the table and cannot find his.

Am I just stupid, or am I trying to do something Ransack just wasn't done?

+6
source share
1 answer

Just for everyone who wants to see how I did it:

In the model where I defined end_date

 def end_date start_date + length.days end 

Then I added the "ranksacker" method to: 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 execute the above sentence, but I am much more familiar with SQL than with Ruby / Rails, so it worked for me so open.

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

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

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

When you click this link, you will receive a query line by line:

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

Again, a quick disclaimer, I’ve been studying Rails and Ruby for about 2 weeks based on the PHP background, so I don’t need an expert and it can be terribly inefficient or much better than the “rails way” about which I just do not know.

+10
source

All Articles