Search code examples
sqlruby-on-railspostgresqljson-apijsonapi-resources

JSONAPI Resources, need a filter for the last record


so I'm looking at creating a filter for a JSONAPI resource where I'll grab anything created within the last 10 minutes and return only one result if something's there.

Problem, when I call .last(1) on the returned records I get an error:

"exception": "undefined method `order' for #<Array:0x007fde4770bcf0>"

My non-breaking query is this:

records.where(user_id: user_id, updated_at: ten_minutes_ago..current_time)

Any help? I'd like to do this on the Rails-side rather than deal with a mangle of results (or no results) on our front-end. Thanks!


Solution

  • Okay, so the deal is this.

    In order to grab only 1 record you'll probably have to overwrite/define your own paginator, like so:

    paginator :none
    

    I'd put it after your attributes and before your filters. Cool? Cool. Next, you can just do your basic Rails querying:

    records.where(user_id: user_id, updated_at: ten_minutes_ago..current_time)
    .order(id: :desc)
    .limit(1)
    

    You need to set your paginator or else the defaults or whatever you've defined will overwrite your limit query. Sweet. Easy.