繁体   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