[英]Ruby on Rails executing database query
I am trying to execute some particular query on the button click in Ruby on Rails.我正在尝试对 Ruby on Rails 中的按钮单击执行一些特定查询。 I have created a table histories.
我创建了一个表历史记录。 In the beginning it is showing all the data.
一开始它显示所有数据。 Here is my haml page
这是我的 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
Now there is a text box.现在有一个文本框。 I want to do it in such a way that when I click search it will execute the query and show data whose username is entered in the box.
我想这样做,当我单击搜索时,它将执行查询并显示在框中输入用户名的数据。
Can somebody help me on this?有人可以帮我吗?
Thank you and Regards谢谢和问候
you can do a simple search to return that data.您可以进行简单的搜索以返回该数据。 something like this
像这样的东西
(model) history.rb (模型)history.rb
def self.search(search)
where("title LIKE ?", "%#{search}%")
end
*this is using SQLLite *这是使用SQLLite
(controller)history_controller.rb (控制器)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/view) (哈姆/视图)
= 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.