아직 검색 기능의 구현에 소모되고 있습니까? 순간에 구현할 수 있는 Gem 'ransack'
이번에는 검색 기능을 폭속으로 구현할 수 있는 Gem
Ransack
입니다.
아니 - 이것은 굉장히 편리합니다.
검색 기능은 자연스럽게 높아?
라고 생각했지만,
이 Gem을 사용하면 30분 정도로 실현할 수 있습니다.
다시 Gem 굉장하다는 느낌입니다.
(어휘력)
그럼 빨리 가자.
우선은
gem 'ransack'
Gemfile에 넣습니다.
% bundle install
잊지 않고
라우팅 이동
 resources :books do
    collection do
      get 'search'
    end
  end
라우팅은
         search_books GET      /books/search(.:format)                                                                  books#search
이런 느낌이 듭니다.
collection과 비슷한 것에 멤버가 있습니다.
 member do
      get 'search'
 end
로 설정하면 라우팅에 ID를 포함할 수 있습니다.
         search_books GET      /books/:id/search(.:format)                                                                  books#search
이번에는 book의 데이터베이스 안에 있는 tag_name이라는 열을 검색할 수 있도록 하고 싶기 때문에 이렇게 했습니다.
다음은 뷰를 만듭니다.
rails g controller books  search
이렇게 하면 컨트롤러와 search의 View를 만들 수 있습니다.
컨트롤러 컨트롤러♪
books_controller.rbclass BooksController < ApplicationController
  before_action :search_book, only: [:index, :search]
  def index
   @books =Book.all
   @book =Book.includes(:user)
   set_book_column 
  end
  def search
    @results = @p.result
    @book = @results.includes(:book)
  end
  private
  def search_book
    @p = Book.ransack(params[:q]) 
  end
  def set_book_column
    @book_name = Book.select("tag_name").distinct 
   end
end
이런 느낌입니다.
Book.select("tag_name").distinct
tag_name에 검색하려는 요소를 넣습니다.
before_action 넣으면
무엇보다 빨리 읽어줍니다.
다음은 View입니다!
books/index.html.reb<%= search_form_for @p, url: search_books_path do |f| %>
    <%= f.label :tag_name_cont, 'タグ名' %>
    <%= f.text_field  :tag_name_cont, placeholder: "タグの名前で検索" %>
    <br>
    <%= f.submit '検索' %>
<% end %>
search_form_for 메소드는 ransac 특정 메소드입니다.
두 번째 줄에 쓰여진 tag_name_cont의 cont는
대체로 맞으면 검색에 걸린다.
라는 녀석입니다.
eq로 하면 똑같은 녀석밖에 걸리지 않게 됩니다.
그 밖에도 몇가지 있으므로 봐 주세요!
 Ransack 추천
검색 결과 화면 만들기
books/search.html.erb   <h1 class="search-forms">
     検索結果
   </h1>
<head class ="search-book-list">
  <div class="book-chosen">
  <%# 検索該当商品一覧 %>
   <% if @results.length !=0 %>    
    <% @results.each do |result| %>
     <br>
     <div class="sec1title">
    <div class="item-show">
          <h2 class='border01'>
            <%= result.genre.type %>
             <%= link_to "/books/#{result.id}" do %>
        <%end %>
          </h2>
        <%= image_tag result.image, id: 'slideshow' if result.image.attached? %>
        <div class="item-info" >
          <h2 id ='item-name'>
            <%= result.name %>
          </h2>
            <form class="item-content-show">
            <%= result.content %>
            </form>
        </div>
        <br />
       </div>
     </div>
    <% end %>
   <% else %>
    <br/>
   該当する商品はありません
   <br/>
   <br/>
<div>
   <%=link_to  "ホームへ戻る",root_path%>
</div>
   <% end %>
   <br>
  </div>
<%# ホームボタン %>
   <%= render "shared/sidebar" %>
 </head>
dekita! 
컨트롤러에서
 def search
    @results = @p.result
    @book = @results.includes(:book)
  end
이렇게 표기하고 있기 때문에 @result
값을 꺼내고 있습니다.
이상으로 설명은 끝납니다.
환경 Ruby on rails
뭔가 실수가 있으면 언제든지 코멘트 부탁드립니다! !
                
                    
        
    
    
    
    
    
                
                
                
                
                    
                        
                            
                            
                            Reference
                            
                            이 문제에 관하여(아직 검색 기능의 구현에 소모되고 있습니까? 순간에 구현할 수 있는 Gem 'ransack'), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다
                                
                                https://qiita.com/shunichfukui/items/846f35e8aac26af49428
                            
                            
                            
                                텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
                            
                            
                                
                                
                                
                                
                                
                                우수한 개발자 콘텐츠 발견에 전념
                                (Collection and Share based on the CC Protocol.)
                            
                            
                        
                    
                
                
                
            
gem 'ransack'
% bundle install
 resources :books do
    collection do
      get 'search'
    end
  end
         search_books GET      /books/search(.:format)                                                                  books#search
 member do
      get 'search'
 end
         search_books GET      /books/:id/search(.:format)                                                                  books#search
rails g controller books  search
class BooksController < ApplicationController
  before_action :search_book, only: [:index, :search]
  def index
   @books =Book.all
   @book =Book.includes(:user)
   set_book_column 
  end
  def search
    @results = @p.result
    @book = @results.includes(:book)
  end
  private
  def search_book
    @p = Book.ransack(params[:q]) 
  end
  def set_book_column
    @book_name = Book.select("tag_name").distinct 
   end
end
<%= search_form_for @p, url: search_books_path do |f| %>
    <%= f.label :tag_name_cont, 'タグ名' %>
    <%= f.text_field  :tag_name_cont, placeholder: "タグの名前で検索" %>
    <br>
    <%= f.submit '検索' %>
<% end %>
   <h1 class="search-forms">
     検索結果
   </h1>
<head class ="search-book-list">
  <div class="book-chosen">
  <%# 検索該当商品一覧 %>
   <% if @results.length !=0 %>    
    <% @results.each do |result| %>
     <br>
     <div class="sec1title">
    <div class="item-show">
          <h2 class='border01'>
            <%= result.genre.type %>
             <%= link_to "/books/#{result.id}" do %>
        <%end %>
          </h2>
        <%= image_tag result.image, id: 'slideshow' if result.image.attached? %>
        <div class="item-info" >
          <h2 id ='item-name'>
            <%= result.name %>
          </h2>
            <form class="item-content-show">
            <%= result.content %>
            </form>
        </div>
        <br />
       </div>
     </div>
    <% end %>
   <% else %>
    <br/>
   該当する商品はありません
   <br/>
   <br/>
<div>
   <%=link_to  "ホームへ戻る",root_path%>
</div>
   <% end %>
   <br>
  </div>
<%# ホームボタン %>
   <%= render "shared/sidebar" %>
 </head>
 def search
    @results = @p.result
    @book = @results.includes(:book)
  end
Reference
이 문제에 관하여(아직 검색 기능의 구현에 소모되고 있습니까? 순간에 구현할 수 있는 Gem 'ransack'), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://qiita.com/shunichfukui/items/846f35e8aac26af49428텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
                                
                                
                                
                                
                                
                                우수한 개발자 콘텐츠 발견에 전념
                                (Collection and Share based on the CC Protocol.)