Ruby on rails order_by two attributes - ruby-on-rails

I have a table and in this table i need the finished attribute if its null to be first but at the same time i want the due date to be ordered asc
def all_cases
#cases=Case.order("finished ASC NULLS FIRST").order(due_date: :asc).paginate(page: params[:page], per_page: 20)
if params[:search]
#search_term = params[:search]
#cases = Case.order("finished ASC NULLS FIRST").order(due_date: :asc).casesearch_by(#search_term).paginate(page: params[:page], per_page: 20)
else
#cases = Case.order("finished ASC NULLS FIRST").order(due_date: :asc).order(sort_columnn + " " + sort_direction).paginate(page: params[:page], per_page: 20)
end
end
This code added the the finished nulls to be first but not sorted the due date
thanks in advance

Depends on what you want
Case.order("finished IS NOT NULL").order(due_date: :asc)
this line of code will ordered by due_date first than ordered by finished attribute,
so in front of the records you get will be record which finished is null.
Case.order(due_date: :asc).order("finished IS NOT NULL")
this line of code will ordered by finished attribute first than ordered by due_date,
so in front of the records you get will be record which due date is smaller.

Related

Rails: SQLite3::SQLException: near "from": syntax error

I have an issue with a sort by year filter on my rails app; when i attempt to select a year from my view, the app crashes with this error: SQLite3::SQLException: near "from": syntax error
The code(passed down from the previous dev who has moved on) for the filter in my control is this:
#posts = Post.where('extract(year from sort_date) = ?', params[:year])
.paginate(page: params[:page], per_page: 5)
.order('sort_date DESC')
render 'index'
end
i might be wrong but i am assuming it's the 'extract(year from sort_date) = ?' in the code? but i am unsure, also for reference the reference parameter is: {"year"=>"2017"}
I attempted to make it look more like a postgres query("EXTRACT(year FROM sort_date) = ?" but still it fails, with the exact same SQL error(Rails: SQLite3::SQLException: near "from")
SQLITE3 does not support the extract() function. You have to use strftime().
#posts = Post.where("strftime('%Y', sort_date) = ?", params[:year])
.paginate(page: params[:page], per_page: 5)
.order('sort_date DESC')
render 'index'
end

Pagination breaks when I add a join and group statement to a query?

I have an index page with Subscriptions. A Subscription has_many SubscriptionVersions and I need to order them based on the latest SubscriptionVersions authorized_at date.
This is my controller action
def index
#subscriptions = current_account.subscriptions
.includes(:plan, :user)
.joins("INNER JOIN subscription_versions
ON subscription_versions.subscription_id = subscriptions.id")
.group("plans.id, subscriptions.id, users.id")
.order("MAX(subscription_versions.authorized_at) ASC")
.paginate(page: params[:page], per_page: 20)
end
Removing the join and order statements, pagination works fine, but if I add them the results are not paginated.
What is going on and why?

Sorting a result defined by remote parameters

i have this index action:
def index
limit = params[:limit]
page = params[:page]
sort = params[:sort].split(',')
#term = nil
if params[:search]
#term = params[:search]
#lessons = policy_scope(Lesson).search(#term)
.order("#{sort[0]} #{sort[1].upcase}")
.paginate(page: page, per_page: limit)
else
#lessons = policy_scope(Lesson).order("#{sort[0]} #{sort[1].upcase}")
.paginate(page: page, per_page: limit)
end
end
which is fed by a vuejs frontend with a vuetify datatable and its purpose is to send out an array of lesson objects, filtered and sorted by the frontend.
this works pretty good with default rails..
however, with the mobility gem involved there is no fieldname "title" for example or "title_en", so the order stops working. in mobility you have some "fake column names" and it automagically handles it to search for the value in a key-value table ( https://github.com/shioyama/mobility#getting-started )
so i sat me down and fired up the console and figured out that:
.order(title: :desc) - works
.order(title_en: :asc) - works
everything with strings involved, like .order('title DESC') or .order('title_en ASC') does not work and results in an error like
ActionView::Template::Error (PG::UndefinedColumn: ERROR: column
"title_en" does not exist LINE 1: SELECT "lessons".* FROM "lessons"
ORDER BY title_en ASC LIMI...
is there a way i could get this working? maybe there is something to generate title: out of 'title'? Or some other magic?
thanks!
You can call the order method like this instead:
.order(sort[0] => sort[1])
Passing "a" => "b" to a method is the same as passing "a": "b".

How use order by condition

Is it possible to sort the data on a condition?
For example, figuratively, .order( "expiration_date <?", Time.current, :desc )
The ORDER BY keyword is used to sort the result-set by one or more columns.
The ORDER BY keyword sorts the records in ascending order by default. To sort the records in a descending order, you can use the DESC keyword.
you can sort by using something like :-
sorted = #records.sort_by &:created_at
or try where by first getting the resultset and then sorting it:-
#records.where( "expiration_date <?", Time.current).order( :created_at, :desc )
Moreover you can paginate easily;-
#records.paginate(:page => params[:page], :per_page => 15)#.order(" created_at ASC")

How to paginate over multiple models?

Suppose I have three or more models with the same table schema and the same number of records.
ford
----
id
model
toyota
----
id
model
chevrolet
----
id
model
I want to create a webpage with pagination where I display all three tables interleaved by id. For example:
id model
---- -----
1 Fusion
1 Corolla
1 Camaro
2 Explorer
2 Camry
2 Volt
I attempted to do this with the following controller:
class CarsController < ApplicationController
def index
#cars = []
#ford = Ford.paginate(:page => params[:page], :per_page => 10)
#toyota = Toyota.paginate(:page => params[:page], :per_page => 10)
#chevrolet = Chevrolet.paginate(:page => params[:page], :per_page => 10)
for i in 0..#ford.size-1 do
#cars << #ford[i]
#cars << #toyota[i]
#cars << #chevrolet[i]
end
end
end
Pagination works up to the last page. I get an error in the last page because less than 10 records are returned. The iteration over #cars in the view somehow expects 10 records. Thus, I get a null reference error.
I do not want to get all of the records from the ford, toyota, and chevrolet tables and then paginate. I want to request the records in batches, and then simply display them. My method is very likely the wrong way to do this. Any suggestions? Perhaps, I can create a view and query that?

Resources