Ruby on Rails执行数据库查询

时间:2016-05-10 22:25:28

标签: ruby-on-rails

我正在尝试在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

现在有一个文本框。我希望这样做,当我点击搜索时,它将执行查询并显示在框中输入用户名的数据。

有人可以帮我吗?

谢谢你,问候

1 个答案:

答案 0 :(得分:0)

您可以进行简单搜索以返回该数据。 像这样的东西

(型号)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

(HAML /视图)

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