문제

I know if I'm using scoped methods in a Rails model, I should store the query in a proc object so it's evaluated when I call it, and not when the application is launched. Example:

scope :shifts_last_week, -> { where(date: (Date.today - 7)..(Date.today)) }

Is the same kind of process necessary for class methods in the same model? Are those methods evaluated at launch in the same way, or can I just define the method as follows?

def self.shifts_this_week
  where( date: (Date.today.beginning_of_week(WEEK_START))..(Date.today + 1) )
end
도움이 되었습니까?

해결책

The answer is that you do not have to do the same lambda wrapping for class method definitions, which are only executed when the method itself is called. The reason why scope is executed when you run the application is because scope is itself a method which ends up calling the 'where' clause (rather than just being a method definition). Method definitions themselves do not get executed until the method they define is called.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top