"尋尋覓覓,冷冷清清"
來加入可以快速搜尋姓名的功能
app/views/girbs/index.html.erb
<div class="container">
<h1>Index Page of Girb</h1>
<%= form_tag(girbs_path, :method => "get", id: "search-form") do %>
<%= text_field_tag :search, params[:search], placeholder: "Search Name" %>
<%= submit_tag "Search", :name => nil %>
<% end %>
<p></p>
<div class="row">
.
.
.
到 app/models/girb.rb 增加 self.search
class Girb < ActiveRecord::Base
has_many :bangs, dependent: :destroy
def self.search(query)
where("name like ?", "%#{query}%")
end
end
去修改 controller 裡的 index
app/controllers/girb_controller.rb
class GirbsController < ApplicationController
def index
if params[:search]
@girbs = Girb.search(params[:search]).order("created_at DESC")
else
@girbs = Girb.all.order("created_at DESC")
end
end
def like
@girb = Girb.find(params[:id])
@girb.like += 1;
@girb.save
redirect_to(girbs_path)
end
def on_click_bang
@girb = Girb.find(params[:id])
@girb.bangs.create
redirect_to(girbs_path)
end
def new
@girb = Girb.new
end
def create
@girb = Girb.new(girb_params)
if @girb.save
redirect_to(girbs_path)
else
render :new
end
end
def show
@girb = Girb.find(params[:id])
end
def edit
@girb = Girb.find(params[:id])
end
def update
@girb = Girb.find(params[:id])
if @girb.update(girb_params)
redirect_to girbs_path
else
render :edit
end
end
def destroy
@girb = Girb.find(params[:id])
@girb.destroy
redirect_to girbs_path
end
private
def girb_params
params.require(:girb).permit(:name, :email, :like)
end
end
現在在搜尋框輸入你想要的關鍵字
就可以跑出過濾後的結果了