The questioner
The questioner

Reputation: 724

Rails 4 scope with multiple conditions

I want to show active users within 1 day.

The Member model and scope:

time_range = (Time.now - 1.day)..Time.now
scope :active, -> { where(created_at: time_range, gold_member: true, registered: true) }

However, when I call

@member = User.active

The below error rendered:

NoMethodError: undefined method `call' for #<User::ActiveRecord_Relation:0x07fe068>

Please advise.

The backtrace:

  from /Users/jason/.rbenv/versions/2.1.4/lib/ruby/gems/2.1.0/gems/activerecord-4.1.7/lib/active_record/relation/delegation.rb:136:in `method_missing'
  from /Users/jason/.rbenv/versions/2.1.4/lib/ruby/gems/2.1.0/gems/activerecord-4.1.7/lib/active_record/relation/delegation.rb:99:in `method_missing'
  from /Users/jason/.rbenv/versions/2.1.4/lib/ruby/gems/2.1.0/gems/activerecord-4.1.7/lib/active_record/scoping/named.rb:151:in `block (2 levels) in scope'
  from /Users/jason/.rbenv/versions/2.1.4/lib/ruby/gems/2.1.0/gems/activerecord-4.1.7/lib/active_record/relation.rb:292:in `scoping'
  from /Users/jason/.rbenv/versions/2.1.4/lib/ruby/gems/2.1.0/gems/activerecord-4.1.7/lib/active_record/scoping/named.rb:151:in `block in scope'
  from (irb):48
  from /Users/jason/.rbenv/versions/2.1.4/lib/ruby/gems/2.1.0/gems/railties-4.1.7/lib/rails/commands/console.rb:90:in `start'
  from /Users/jason/.rbenv/versions/2.1.4/lib/ruby/gems/2.1.0/gems/railties-4.1.7/lib/rails/commands/console.rb:9:in `start'

Upvotes: 3

Views: 5492

Answers (1)

Marek Lipka
Marek Lipka

Reputation: 51191

It won't fix your error, but there's a problem with the way you define your scope. Before you do it, you define local variable time_range. But the problem is, you define it in the body of your ActiveRecord class, so it will be evaluated only one time in production environment, when the class is loaded. You should evaluate your time range inside of lambda:

scope :active, -> {
  where(created_at: (Time.now - 1.day)..Time.now, gold_member: true, registered: true)
}

Upvotes: 1

Related Questions