Rails 4具有多个条件的范围

时间:2014-12-16 07:36:52

标签: ruby-on-rails ruby-on-rails-4 activerecord scope

我想在1天内向活跃用户展示。

会员模型和范围:

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

然而,当我打电话

@member = User.active

呈现以下错误:

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

请告知。

回溯:

  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'

1 个答案:

答案 0 :(得分:1)

它不会修复您的错误,但是您定义范围的方式存在问题。在执行此操作之前,您需要定义局部变量time_range。但问题是,您在ActiveRecord类的主体中定义它,因此在加载类时,它将仅在生产环境中进行一次计算。你应该评估你在lambda内的时间范围:

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