노래하듯 이야기하고, 춤추듯 정복하라.

[Ruby On Rails] 레일즈 앱에 검색기능 구현하기 본문

프로그래밍/Ruby & Rails

[Ruby On Rails] 레일즈 앱에 검색기능 구현하기

hyeoke 2019. 1. 29. 14:25

[ 검색 기능 구현 ]

- 주요 참고자료: https://blog.naver.com/kbs4674/221379111562


# 서두

안녕하세요 모닝버드입니다. 오늘은 평소보다 30분 일찍 출근했는데, 그냥 졸리네요...... 아무튼 오늘도 화이팅 빠샤!

자 그럼 오늘은 레일즈 앱에 검색 기능을 넣어 보겠습니다. 기존의 젬들인 Sunspot이나 ElasticSearch 같은 젬을 사용하기보다 직접 구현 해 보겠습니다. 이유는 기존 젬들이 한글에 특화되어 있지 않아 형태소 분석 문제가 있습니다.


# search 컨트롤러 생성

$ rails g controller search result


# controllers/search_controller.rb

def result
    @contents = eval(params[:param_contents]).where('created_at >= :years_ago', :years_ago => Time.now - 1.years).where("title like ?", "%#{params[:search_text]}%")
    @products = eval(params[:param_products]).where('created_at >= :years_ago', :years_ago => Time.now - 1.years).where("name like ?", "%#{params[:search_text]}%")
end

* :bulletin => 소팅할 모델_모델을 파람형태로 받아서 전달할 수 있다는 것!, 단 eval 함수를 사용해야함.

* eval 함수의 역할: rails 코드의 일환으로 변환을 시켜주는 함수, (eval함수를 사용하지 않으면 모델을 String으로 인식함)


# views/search/_search_form.html.erb

<%= form_tag(search_result_path, method: "get") do %> <%# method를 get방식으로 받아내며, parameter가 /searches/result로 넘어갈 예정. %>
    <%= label_tag(:div, "검색 단어 :") %>
    <%= text_field_tag(:search_text) %> <%# 검색 하고자 하는 단어를 입력받음, 이 떄 name은 [검색 단어] %>
    <%= hidden_field_tag(:param_contents, "#{contents}") %> <%# 모델 이름을 자동으로 받아냄 (name은 [bulletin], value 값에는 [모델 이름]이 들어감) %>
    <%= hidden_field_tag(:param_products, "#{products}") %>
    <%= submit_tag("검색") %>
<% end %>


# controllers/application_controller.rb

before_filter :search_models

def search_models
    @contents_search = Content.all
    @products_search = Product.all
end

* before filter :search_models => views/layout/application.yml에 데이터가 담긴 변수에 접근할 수 있음..!



# views/layout/application.html.erb

<%= render 'search/search_form', contents: @contents_search.klass, products: @products_search.klass %>

* klass 함수(메소드)는 무엇? 변수가 가진 정보 중, 모델 이름을 추출해내는 메소드 (★) 


# 전체적인 순서 복습

1. search 컨트롤러를 생성한다 (result 액션과 함께)

2. application 컨트롤러에서 검색 텍스트로 필터링할 모델들을 할 당한다. => def search_models 

3. search_form을 만든다. => hidden_field input 태그로 application 컨트롤러에서 할당한 모델 받기, 검색 창 만들기

4. search 컨트롤러의 result 액션에서 검색 결과 만들기(소팅하기) => eval함수를 이용하여 params에 담긴 모델 받기 + 소팅조건 세팅하기



[ 꿀Tip -> rails where 쿼리문에서 중복 조건 주기 ]

- 참고 링크: https://stackoverflow.com/questions/32753168/rails-5-activerecord-or-query


1. A && B

Post.where(a).where(b)

2. A || B

Post.where(a).or(Post.where(b))

3. (A && B) || C

Post.where(a).where(b).or(Post.where(c))


Comments