iT邦幫忙

DAY 15
1

Rails. Really, I love study.系列 第 15

尋找。

  • 分享至 

  • xImage
  •  

"尋尋覓覓,冷冷清清"


來加入可以快速搜尋姓名的功能

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

現在在搜尋框輸入你想要的關鍵字

就可以跑出過濾後的結果了


上一篇
刪除。
下一篇
排序。
系列文
Rails. Really, I love study.30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言