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
有帮助吗?

解决方案

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top