Rails: SQLite3::SQLException: near "from": syntax error - ruby-on-rails

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

Related

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".

Ruby on rails order_by two attributes

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.

Where Clause - Ruby on Rails

I am new to Ruby on Rails and am having trouble with a simple where with a model.
When I try to do Test #1 the results are out of order. New items get pushed to the bottom no matter what.
def index
#user = User.where(:status => false).order(last_name: :desc).all
end
If I enter this into rails console it doesn't work also but if I remove the all it works perfectly in rails console but doesn't work in the UsersController.
What is the proper way to do a where clause with an order? Thanks for your help!
UPDATE:
I have updated the code to the following but the results are still out of order:
def index
#user = User.where(status: false).order('last_name DESC')
end
You should use order('last_name DESC') instead of order(last_name: :desc).
order(last_name: :desc) will produce sql like (That's why your order doesn't work):
ORDER BY '---\\n:last_name: :desc\\n'
order('last_name DESC') will produce sql right:
ORDER BY last_name DESC
Rails 4
def index
#user = User.where(status: false).order('last_name DESC')
end

How can I order when using pagination?

This might be quite simple question.
Here's my code. Then I want to sort #codes ordered by the column code.user.last_active_at
#here, I retrieve only the records that contains particular keyword.
#search = Code.search do
fulltext params[:search]
with(:community_id, community_search)
paginate :page => 1, :per_page => 1000000
end
#Here, I try pagination. 10 records per each page.
#codes = #search.results
#codes = Kaminari.paginate_array(#codes).page(params[:page]).per(10)
I want to sort them ordered by the column #code.user.last_active_at
How can I do that?
I tried this
#codes = Kaminari.paginate_array(#codes.joins(:user).order('user.last_active_at DESC')).page(params[:page]).per(10)
But it returned this error
NoMethodError (undefined method `joins' for #
<Sunspot::Search::PaginatedCollection:0x0000001ca851a8>):
app/controllers/codes_controller.rb:95:in `index'
How can I sort while I'm using Kaminari pagination?
Kaminari not affect on sorting. first you have to sort and then get page(x).per(x)
so for example in your controller
#codes = #search.results
#codes = #codes.joins(:user).order('user.last_active_at DESC').page(params[:page]).per(10)
edit:
after check sunspot documentation I think you can make something like
#search = Code.search(include: :user) do
fulltext params[:search]
with(:community_id, community_search)
order_by('user.last_active_at DESC')
#paginate :page => params[:page], :per_page => 10 you can add this and not use Kaminari
end
you can try joins except include

PostgreSQL Ruby Heroku Problems

This search condition works fine in MySQL, and SQLite but fails in PostgreSQL:
CONTROLLER:
#inventories = Inventory.search(params[:search], params[:page])
MODEL:
def self.search
paginate :per_page => 10,
:page => page,
:conditions => ['part_number = ? OR item LIKE ? OR catalognumber LIKE ?', "#{search}", "%#{search}%", "%#{search}%"],
:order => 'item'
end
IT produces this error in HEROKU's PostgreSQL log:
ActiveRecord::StatementInvalid (PGError: ERROR: invalid input syntax for integer: ""
2011-06-11T20:25:46+00:00 app[web.1]: : SELECT * FROM "inventories" WHERE (part_number = E'' OR item LIKE E'' OR catalognumber LIKE E'') ORDER BY item LIMIT 10 OFFSET 0):
How can I fix this?
SOLUTION... This is an issue of using LIKE rather than ILIKE
http://www.postgresql.org/docs/8.3/static/functions-matching.html
Presumably, one of those fields is expecting an integer, and Postgres is a lot less permissive on this front than MySQL. I shouldn't have any quotes. (It should be zero, or no field at all, instead.)

Resources