Question

I have a model in which I have implemented a method that returns a set of records. Is it possible refer them in Arel?

class A < ActiveRecord::Base
  #associations here

  def self.mymeth
    #return a set of records based on a query
    B.select(col).joins(:cs).where(some_condition)
  end

end

class B < ActiveRecord::Base
  #associations here
end

class C < ActiveRecord::Base 
  #associations here    
end

Now how can I refer mymeth to something like

  A.joins(:mymeth).where(condition).count
Was it helpful?

Solution

Aren't you looking for scopes ?

class A < ActiveRecord::Base

  scope :myscope, lambda { joins(:b).where(column: true) }
end

You can then call a scope with the following :

A.mymeth.where(col: false)

All the SQL conditions you will have added in the scope will be automatically added to your query when called.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top