notaceo
notaceo

Reputation: 1093

Undefined method 'criteria' for Ruby Object

undefined method `criteria' for #<Timeclock:0x00000106a969b8>

MongoMapper - MongoDB - tried to define the following scope in the Timeclock class:

  scope :last_clock_time, ->(session) do
    where({:user => session[:user_id]}).sort(:created_at.desc).first() 
  end

I call Timeclock.last_clock_time(session) and I get the error at the top.

Not even sure what 'criteria' is in this case

EDIT :

So I post a question and then go play around with it - I changed this:

scope :last_clock_time, ->(session) do
        where({:user => session[:user_id]}).sort(:created_at.desc)
      end

And then I call Timeclock.last_clock_time.first() and it works

Why?

Upvotes: 1

Views: 373

Answers (1)

mu is too short
mu is too short

Reputation: 434665

Your original last_clock_time is not really a scope at all, it is just a query that returns at most one Timeclock. A scope is supposed to return a query (AKA "criteria" or "search criteria") so that you can chain it:

Model.scope1.scope2.where(...)...

When you call first on the query, you get a Timeclock instance (or nil of course) and model instances don't have criteria methods, queries and model classes do have a criteria method and that's the sort of thing that a scope is supposed to return.

Somewhere something is assuming that your scope really is a scope and calling criteria on its return value to work with the underlying query. But your scope is a lie because it returns that wrong sort of thing.

When you drop the first call, your scope stops being a lie and returns what a scope is supposed to return. Once your scope stops lying, everything starts to work.

Upvotes: 2

Related Questions