簡體   English   中英

Ruby on Rails 執行數據庫查詢

[英]Ruby on Rails executing database query

我正在嘗試對 Ruby on Rails 中的按鈕單擊執行一些特定查詢。 我創建了一個表歷史記錄。 一開始它顯示所有數據。 這是我的 haml 頁面

%h1 History

%br
%br

%table#views
  %tbody
    %tr
      %td
      %td
        %input{:required => "", :type => "text"}
      %td
        %input{:required => "", :type => "submit", :value => "Search"}


%table#houses
  %thead
    %tr
      %th UserName
      %th User ID
      %th Email
      %th Rented House
      %th Start Date
      %th End Date
      %th Total Cost ($)
      %th Rating
  %tbody
    - @histories.each do |history|
      %tr
        %td= history.user_name
        %td= history.user_id
        %td= history.email
        %td= history.house_address
        %td= history.start_date
        %td= history.end_date
        %td= history.total_cost
        %td= history.rating

= link_to 'Back to Welcome page', users_path

現在有一個文本框。 我想這樣做,當我單擊搜索時,它將執行查詢並顯示在框中輸入用戶名的數據。

有人可以幫我嗎?

謝謝和問候

您可以進行簡單的搜索以返回該數據。 像這樣的東西

(模型)history.rb

def self.search(search)
  where("title LIKE ?", "%#{search}%")
end

*這是使用SQLLite

(控制器)history_controller.rb

  def index
    @histories = Histories.all
    if params[:search]
      @histories = Histories.search(params[:search]).order("created_at DESC")
    else
      @histories = Histories.all.order('created_at DESC')
    end
  end

(哈姆/視圖)

 = form_tag(history_path, :method => "get", id: "search-form") do
  = text_field_tag :search, params[:search], placeholder: "Search Username", :class => "form-control"

暫無
暫無

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

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