2011-03-17 4 views
1

옵션 레일을 기준으로 기준을 연결하려고합니다. 매개 변수.Mongoid 옵션을 별도의 문장으로 연결하는 방법은 무엇입니까?

선택한 태그를 기반으로 동시에 검색 할 수있는 으로 필터링 할 수 있기를 원합니다.

여기 모든 상황에서 작동하는 현재의 코드입니다 : 내가 시도

if params[:tag] and params[:search] 
    @notes = Note.tagged_with_criteria(params[:tag]).full_text_search(params[:search]) 
elsif params[:tag] 
    @notes = Note.tagged_with_criteria(params[:tag]) 
elsif params[:search] 
    @notes = Note.full_text_search(params[:search]) 
end 

단순히 if 문없이

@notes = Note.tagged_with_criteria(params[:tag]).full_text_search(params[:search]) 

를 사용하지만, 다음 PARAMS 중 하나만 인 경우 주어, 모든 노트가 반환됩니다.

각 메소드 (tagged_with_criteria 및 full_text_search)는 해당 매개 변수가 nil/empty 인 경우 이 Note.criteria를 반환합니다.

Mongoid 기준을 연결하는 더 간단하고 우아한 방법이 있습니까?

차라리 기준에 하나씩 대신 이상한 "만약 PARAMS는 [...] params가 [...]"일이 ..

UPDATE를 수행하는 데에 압정으로 고정 유지하는 것

: 여기에 현재의 방법은 다음과 같습니다 그런 상황에서

def tagged_with_criteria(_tags) 
    _tags = [_tags] unless _tags.is_a? Array 
    if _tags.empty? 
    criteria 
    else 
    criteria.in(:tags => _tags) 
    end 
end 


    def self.full_text_search(query) 
    if query 
     begin 
     regex = /#{query}/ 
     # supplied string is valid regex (without the forward slashes) - use it as such 
     criteria.where(:content => regex) 
     rescue 
     # not a valid regexp -treat as literal search string 
     criteria.where(:content => (/#{Regexp.escape(query)}/)) 
     end 
    else 
     # show all notes if there's no search parameter 
     criteria 
    end 
    end 

답변

4

, 나는 빈 값을 통과 할 때 아무것도하지 않고하는 범위를 수정하는 것입니다.

나는 무슨 일이 벌어지고 있을지 생각한다. params 해시에서 빈 문자열을 얻는 것이므로 코드에 무언가가 입력되었다고 생각하게한다. 이러한 편집으로 스코프를 사용해보십시오.

def tagged_with_criteria(_tags) 
    _tags = Array.wrap(_tags).reject(&:blank?) 
    if _tags.empty? 
    criteria 
    else 
    criteria.in(:tags => _tags) 
    end 
end 

def self.full_text_search(query) 
    if query.present? 
    begin 
     regex = /#{query}/ 
     # supplied string is valid regex (without the forward slashes) - use it as such 
     criteria.where(:content => regex) 
    rescue 
     # not a valid regexp -treat as literal search string 
     criteria.where(:content => (/#{Regexp.escape(query)}/)) 
    end 
    else 
    # show all notes if there's no search parameter 
    criteria 
    end 
end 
+0

위의 코드를 참조하십시오. –

+0

아무 것도하지 않으면 아무 것도 반환하지 않습니까? –

+0

아니요, 수정하지 않고 기준을 반환하는 것을 의미합니다. –

관련 문제