1
我想爲Sinatra上的簡單產品庫存應用程序提供基本的搜索功能,但不知道如何使控制器和視圖正確輸出所有具有類似名稱的產品到結果頁面。在Ruby中的基本搜索Sinatra ActiveRecord
SearchPage.erb:
<form action="/search", method="post"> <input type="text" name="product[name]">
控制器:
post '/search' do
@Products = Product.find_by(name: params[:product][:name])
@Products = Product.all(:name.like => "%#{params[:name]}%") #found this on another question
erb :"result"
end
Result.erb
<% @Products.each do |product| %>
<%=product.name %>
<%=product.details %>
編輯:我是能夠使搜索工作BA根據以下代碼建議。謝謝!:
Search.erb查看
<form action="/search", method="get">
<input type="text" name="search">
控制器
get '/search' do
@products = Product.all
if params[:search]
@products = Product.search(params[:search])
else
@products = Product.all
end
erb :'results'
end
型號
class Product < ActiveRecord::Base
def self.search(search)
where("name like ?", "%#{search}%")
end
Results.erb查看
<% if @products.present? %>
<table>
<td>Product Name</td><td>Company</td>
<% @products.each do |product| %>
<tr><td><a href="/products/<%= product.id %>"><%=h product.name %></a> </td>
<td><%=h product.company.name %></td>
<% end %>
<% else %>
<p>There are no Products containing the term(s) <%= params[:search] %>.</p>
<% end %>
</table>
Woops你說得對。我的錯。我會編輯 – luke
謝謝!我用每個做結果頁面,而不是渲染和更新代碼 –