는 방법으로 다음을 사용하려고 할 수 얇은 컨트롤러를 유지하고 스파게티 코드를 방지하려면 :
컨트롤러 :
def index
@questions = Question.filter(params.slice(:status, :only_images, ...) # you still can chain with .order, .paginate, etc
end
모델 :
def self.filter(options)
options.delete_if { |k, v| v.blank? }
return self.scoped if options.nil?
options.inject(self) do |scope, (key, value)|
return scope if value.blank?
case key
when "status" # direct map
scope.scoped(:conditions => {key => value})
when "only_images"
scope.scoped(:conditions => {key => value=="yes" ? true : false})
#just some examples
when "some_field_max"
scope.scoped(:conditions => ["some_field <= ?", value])
when "some_field_min"
scope.scoped(:conditions => ["some_field >= ?", value])
else # unknown key (do nothing. You might also raise an error)
scope
end
end
end
scope.scoped가 무엇을하고 작동하는지 조금 설명해 주시겠습니까? – LuckyLuke
'scope'는 단지 변수 이름이며, 조건이 추가 된 ActiveRecord 객체를 유지합니다. scope.scoped는 익명 범위를 생성합니다. – dimuch
아 맞아. 이해 했어. – LuckyLuke