Rails 4 scope with multiple conditions

I want to show active users for 1 day.

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

      

Below is the error:

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

      

Please advise.

Reverse:

  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'

      

+3


source to share


1 answer


It won't fix your mistake, but there will be a problem with how you define your scope. Before you do that, you are defining a local variable time_range

. But the problem is that you are defining it in the body of your class ActiveRecord

, so it will only be evaluated once in production when the class is loaded. You have to evaluate your time range inside the lambda:



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

      

+1


source







All Articles