Reputation: 2184
I've been doing some edits to an output when working with some records and i've ran into a problem where the sorting option no longer is working.
Initially with how things were created when I would do a @record.class
the output was Record::ActiveRecord_Relation < ActiveRecord::Relation
However now after making my changes the class has changed. So now when I run a @record.class
the output is Array < Object
.
I think this is the root reason why i've ran into this problem.
My code is
@q = @records.search(params[:q])
@records = @q.result(distinct: true).select { |k,_v| k[:disabled] }
@records = @records.order("records.updated_at desc").page(params[:page] || 1).per(params[:per] || 30)
The error I am getting is NoMethodError: undefined method
order' for #`
Now i've tried to workout around this by
@records = @records.sort_by("records.updated_at desc")
@records = @records.paginate.page(params[:page] || 1).per(params[:per] || 30)
However the error with the first line of my solution is @records = @records.sort_by("records.updated_at desc")
I'm not able to get past that line in case there is an error with my paginate
solution.
If anyone could take a look, I would really appreciate it!
Upvotes: 1
Views: 289
Reputation: 107117
The signature you the methods you use look like you are using ransack
.
Instead of loading all records into memory and selecting matching records in Ruby it might be much faster to only load matching records from database in the first place.
Assuming that disabled
is a boolean column in your database, I would advise to change
@q = @records.search(params[:q])
@records = @q.result(distinct: true).select { |k,_v| k[:disabled] }
@records = @records.order("records.updated_at desc").page(params[:page] || 1).per(params[:per] || 30)
to
@q = @records.where(disabled: true).search(params[:q])
@records = @q.result(distinct: true)
@records = @records.order("records.updated_at desc").page(params[:page] || 1).per(params[:per] || 30)
Upvotes: 1
Reputation: 80128
The issue is that you are calling result
, which is causing the SQL query to be executed and data returned from the database. You don't want to do that if you want to continue forming your query using the Arel AST that ActiveRecord uses. You want something closer to this (you'll likely need to adapt):
r = records.where(some_param: some_value, disabled: true) \
.order(updated_at: :desc) \
.page(params[:page] || 1).per(params[:per] || 30)
Upvotes: 1
Reputation: 7279
your @records
is a Ruby array, not an ActiveRecord "array"
You can try @records.sort_by(&:updated_at)
to sort your array
Upvotes: 1