Malek Zalfana
Malek Zalfana

Reputation: 318

How can I order multiple ActiveRecords in rails by time?

In my controller, I needed to add logical operators like || and && in my but it's not working so I thought it would be easier for me to make different variables with each one its own condition and then order them as if they're one using created_at DESC.

@postActivity = PublicActivity::Activity.order("created_at DESC").where( owner_id: current_user.following.ids, key: 'posting' ).limit(20).all
@commentActivity = PublicActivity::Activity.order("created_at DESC").where( key: 'commenting' ).limit(20).all

The conditions are much more complicated than those above. If you could point out a different way then sure do, appreciated. PS. I'm a ruby newbie ..

Upvotes: 1

Views: 503

Answers (2)

Pavel Bulanov
Pavel Bulanov

Reputation: 953

For your specific samples, where conditions are multiplied (and), you can use ActiveRecord scopes - here

They are made for the purpose of naming query conditions that you nicely combine in the code. Add scopes to your model, i.e. classes which inherit from ActiveRecord::Base

class Activity < ActiveRecord::Base
  scope :ordered, -> { order(created_at: :desc) }
  scope :commenting, -> { where(key: 'commenting') }
  scope :limit, -> { limit(20) }
..

And then to combine scopes (and condition) you just chanin

Activity.ordered.commenting.limit...

Meanwhile, there is a default_scope for something you include by default (e.g. order by)

For or condition (smt or smt) it's more complicated - you seems to use Arel.table (which is inside ActiveRecord) - see here for example

Upvotes: 2

bkunzi01
bkunzi01

Reputation: 4561

ANDs and ORs work in controllers, did you mean in a query in your controller? If you are trying to do a complex SQL query you can bypass active record to do the query in raw SQL. Use rails find_by_sql method as shown here: http://guides.rubyonrails.org/active_record_querying.html#finding-by-sql

Upvotes: 1

Related Questions