Home Dynamically adding ActiveRecord scopes
Reply: 1

Dynamically adding ActiveRecord scopes

Huey Published in 2017-12-05 05:42:10Z

I have many scopes that use date ranges to do something, e.g. clicks_between(start_date, end_date). I also have want to support adding in a school year string, where we have an existing SchoolYear that has a start and end methods.

I could do something like:

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

However, I'd rather not have to copy and paste this code everywhere. Is there a way to just dynamically add this scope if the "betweeen" scope exists already?

Wasif Hossain
Wasif Hossain Reply to 2017-12-05 20:04:20Z

Applying the concept of concerns, you may group together dependent scopes inside a module and include that module in the models as you need. Moreover as your scopes do accept arguments, using a class method is the preferred way in place of scopes. For more, please check Passing in arguments.

module Clickable
  extend ActiveSupport::Concern

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

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

In your model:

class SomeModel < ActiveRecord::Base
  include Clickable

class OtherModel < ActiveRecord::Base
  has_many :some_models

Now you can call scopes as usual:


ActiveSupport::Concern api

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.345809 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO