【问题标题】:Dynamically adding ActiveRecord scopes动态添加 ActiveRecord 范围
【发布时间】:2017-12-05 05:42:10
【问题描述】:

我有许多使用日期范围做某事的范围,例如clicks_between(开始日期,结束日期)。我还想支持添加一个学年字符串,我们有一个现有的学年,它有一个开始和结束方法。

我可以这样做:

scope :clicks_during, -> (year) {
    year = Year.new(year) if year.is_a?(Integer)
    send('clicks_between', year.start, year.end) 
}

但是,我宁愿不必到处复制和粘贴此代码。如果“中间”范围已经存在,有没有办法动态添加这个范围?

【问题讨论】:

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


【解决方案1】:

应用关注点的概念,您可以将模块内的依赖范围组合在一起,并根据需要将该模块包含在模型中。此外,由于您的作用域确实接受参数,因此使用类方法是代替作用域的首选方法。更多内容请查看Passing in arguments.

module Clickable
  extend ActiveSupport::Concern

  class_methods do
    def clicks_between(start_date, end_date)
      # ...
    end

    def clicks_during(year)
      year = Year.new(year) if year.is_a?(Integer)
      send('clicks_between', year.start, year.end)
    end
  end
end

在您的模型中:

class SomeModel < ActiveRecord::Base
  include Clickable
end

class OtherModel < ActiveRecord::Base
  has_many :some_models
end

现在你可以像往常一样调用作用域了:

SomeModel.clicks_during(2017)
other_model.some_models.clicks_during(2017)

ActiveSupport::Concern api

【讨论】:

    猜你喜欢
    • 2019-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-11
    • 2011-12-17
    相关资源
    最近更新 更多