제목과 설명 필드 모두와 비교할 간단한 열거 형 및 테스트 쿼리 인 검색 필터 상태를 가진 간단한 목록 페이지가 있습니다. 내 모델의. 내 컨트롤러에서레일스 검색에서 필터 매개 변수를 선택적으로 조합하십시오.
, 나는 이런 식으로 뭔가를하고 싶지 : 나는 조건의 두 가지 유형 (해시와 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
명확하게하기 위해, Rails 2.x에서 "스코프"를 사용할 수 있습니까? 아니면 Rails 3 향상입니까? – GSP
Rails 2.1.0부터 named_scope-s가 추가 된 이후부터 사용할 수 있습니다. 이것은 모든 ActiveRecord 클래스에 대해 정의 된 명명 된 범위 일뿐입니다. http://apidock.com/rails/ActiveRecord/NamedScope/included/class를 참조하십시오. – Voyta