ruby on rails - How do you apply limits and ordering to associations? -
i'm trying create query can following,
category
has_many dates
- query takes location , category
- provides array of categories, ordered number of jobs in category. this, i'm using
default_scope { order(jobs_count: :desc) }
incategory
model, jobs_count counter.
in each category query provides array of jobs
- jobs ordered boolean associated attribute
order.featured
, date (order
belongs_tojob
) - only shows jobs attribute:
open: true
. can done scope. - only shows jobs near location if location present. requires call of class method job.within()
- shows 20 if no category has been set. proving difficult.
is possible in 3 calls database?
attempt @ solution
at high level, first find find jobs in right area, attribute open: true
if need show 20 jobs per category, group jobs category using ruby's group_by
, attempt order them correctly, remove first 20 in each array.
i take ids of these jobs.
i perform database call category table, category.includes(:jobs).where(jobs: { id: job_ids})
. default scopes ensure order correct.
however, i'm getting stuck @ final obstacle! can't seem order jobs come way. default_scope seems being ignored, , don't know how apply order or scope jobs called in category
query.
is correct way approach problem? there easier way? jobs.group_by(...) better - seems require passing in raw sql in ruby docs: http://guides.rubyonrails.org/active_record_querying.html#group
Comments
Post a Comment