문제

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