2010-06-02 2 views
1

제목과 설명 필드 모두와 비교할 간단한 열거 형 및 테스트 쿼리 인 검색 필터 상태를 가진 간단한 목록 페이지가 있습니다. 내 모델의. 내 컨트롤러에서레일스 검색에서 필터 매개 변수를 선택적으로 조합하십시오.

, 나는 이런 식으로 뭔가를하고 싶지 : 나는 조건의 두 가지 유형 (해시와 paramatized 버전)를 혼합 할 수처럼

def index 
    conditions = {} 
    conditions[:status] = params[:status] if params[:status] and !params[:status].empty? 
    conditions[???] = ["(descr = ? or title = ?)", params[:q], params[:q]] if params[:q] and !params[:q].empty? 
    @items = Item.find(:all, :conditions => conditions) 
end 

불행하게도, 그것은 보이지 않는다. 이 일의 "레일 웨이"가 아니면 단순히 이런 끔찍한 일을해야합니까 : 내가 올바르게 생각하고 있지 않다 그래서 만약 용서 최대 절전 모드 및 기준에서 마이그레이션하고있어

has_status = params[:status] and !params[:status].empty? 
has_text = params[:q] and !params[:q].empty? 
if has_status and !has_text 
    # build paramatized condition with just the status 
elsif has_text and !has_status 
    # build paramatized condition with just the text query 
elsif has_text and has_status 
    # build paramatized condition with both 
else 
    # build paramatized condition with neither 
end 

. ..

환경 : 2.3.4

답변

2

당신은 혼합 할 수 해시와 배열 상태 사용 범위 :

hash_conditions = {} 
# build hash_conditions 

items_scope = Item.scoped(:conditions => hash_conditions) 

unless params[:q].blank? 
    items_scope = items_scope.scoped(:conditions => ["(descr = ? or title = ?)", params[:q], params[:q]]) 
end 

... 

items = items_scope.all 

그래서 당신이 할 수있는 나는 ....

참조가 will_paginate 보석 작동되는지 확인하려고 해요 어떤 유형의 조건을 조합하고 일치 시키면 수행 할 때만 쿼리가 실행됩니다. items_scope.all

+0

명확하게하기 위해, Rails 2.x에서 "스코프"를 사용할 수 있습니까? 아니면 Rails 3 향상입니까? – GSP

+0

Rails 2.1.0부터 named_scope-s가 추가 된 이후부터 사용할 수 있습니다. 이것은 모든 ActiveRecord 클래스에 대해 정의 된 명명 된 범위 일뿐입니다. http://apidock.com/rails/ActiveRecord/NamedScope/included/class를 참조하십시오. – Voyta

0
a=[],b=[] 
unless params[:status].blank? 
    a << "status = ?" 
    b << params[:status] 
end 
unless params[:q].blank? 
    a << "(descr = ? or title = ?)" 
    b << params[:q] << params[:q] 
end 
@items = Item.all(:conditions => [a.join(" AND "), b]) 
관련 문제