簡體   English   中英

如何在不使用其他gem的情況下創建Rails搜索欄工具

[英]How can I create a Rails search bar facility without using additional gems

我正在為我們的社區構建一個小型分類應用程序,使人們可以使用僅帶有參數描述和圖像的表格列出要出售的產品。

這兩個參數都在schema.rb中

問題:

我已經將搜索欄嵌入到index.html.erb上,並且還創建了一個空白的show.html.erb。 目前,搜索欄除了看上去很漂亮之外什么做,

我正在努力了解如何進行搜索以詢問描述參數並將結果傳遞到show.html.erb上。

注意:我希望show.html.erb頁及其搜索結果可以使我的索引頁外觀精美,並無需另外安裝gem即可完成此任務。

class PinsController < ApplicationController
before_action :set_pin, only: [:show, :edit, :update, :destroy]
before_action :correct_user, only: [:edit, :update, :destroy]
before_action :authenticate_user!, except: [:index, :show]

def index
@pins = Pin.all.order("created_at DESC").paginate(:page =>   params[:page], :per_page => 15)
end


def show
end


def new
@pin = current_user.pins.build
end


def edit
end


def create
@pin = current_user.pins.build(pin_params)
if @pin.save
  redirect_to @pin, notice: 'Pin was successfully created.'
else
  render :new
end
end


def update
if @pin.update(pin_params)
redirect_to @pin, notice: 'Pin was successfully updated.'
else
render :edit
end
end


def destroy
@pin.destroy
redirect_to pins_url
end


private
# Use callbacks to share common setup or constraints between actions.
def set_pin
  @pin = Pin.find_by(id: params[:id])
end

def correct_user
  @pin = current_user.pins.find_by(id: params[:id])
  redirect_to pins_path, notice: "Not authorized to edit this pin" if @pin.nil?
end

# Never trust parameters from the scary internet, only allow the   white list through.
def pin_params
  params.require(:pin).permit(:description, :image)
end
end  

將您的索引方法更改為是否具有搜索查詢。

def index
  if params[:query]
    @results = Advert.where('lower(description) LIKE ?', '%#{params[:query].downcase}%')
  else
    @results = Advert.all
  end
end

您還可以使用javascript創建過濾器,或者安裝searchkick gem,或者如果您需要真正簡單的安裝rails4-autocomplete

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM