3

In my Deal class, I've added a scope method:

scope :current, -> { where {|d| d.end_date > Date.today} }

It returns the right data, but rather than returning an array that I can count, iterate, etc, it returns an ActiveRecord::QueryMethods::WhereChain, and I can't do anything with that.

I notice that a call to Deal.current starts with "@scope=":

Deal.current                                                                                                                   
  Deal Load (1.0ms)  SELECT "deals".* FROM "deals"
=> #<ActiveRecord::QueryMethods::WhereChain:0x00007fbc61228038
 @scope=
  [#<Deal:0x00007fbc5fdb2400
    id: 7,

I suppose if I knew how to use a "normal" where statement for comparison (rather than equality) such as where(end_date>Date.today) that would band-aid my problem, since a scope method using a simple where statement like scope :posted, -> { where.not(posted_date:nil) } returns a normal useable ActiveRecord.Relation, but I do want to figure out how to use more complex where queries like this one correctly.

1 Answer 1

3

You could use as following:

scope :current, -> { where('end_date > ?', Date.today) }

The block-syntax for a where-call, does not exist in Rails.

You could also look into arel (https://robots.thoughtbot.com/using-arel-to-compose-sql-queries);

deal = Deal.arel_table
Deal.where(deal[:end_date].gt(Date.today))
Sign up to request clarification or add additional context in comments.

1 Comment

Not entirely, no! Using the arel_table, it's still ruby, and not really SQL, but the more advanced queries, the closer to SQL! Can't avoid it forever :).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.