title: Basic Search in Ruby Sinatra ActiveRecord
body: <p>I'm trying to make a basic search function for a simple product inventory app on Sinatra, but don't know how to make the controller and view to properly output all the products which have similar names to a results page. </p>
  
  <p>SearchPage.erb:</p>
  
  <p><code>&lt;form action="/search", method="post"&gt;
  &lt;input type="text" name="product[name]"&gt;</code></p>
  
  <p>Controller:</p>
  
  <pre><code>post '/search' do
  @Products = Product.find_by(name: params[:product][:name])
  @Products = Product.all(:name.like =&gt; "%#{params[:name]}%") #found this on another question
  erb :"result"
  end
  </code></pre>
  
  <p>Result.erb</p>
  
  <pre><code>&lt;% @Products.each do |product| %&gt;
  &lt;%=product.name %&gt;
  &lt;%=product.details %&gt;
  </code></pre>
  
  <hr>
  
  <p>EDIT: I was able to make search work based on the suggestion with the following code. Thanks!:</p>
  
  <p>Search.erb View</p>
  
  <pre><code>&lt;form action="/search", method="get"&gt;
  &lt;input type="text" name="search"&gt;
  </code></pre>
  
  <p>Controller</p>
  
  <pre><code>get '/search' do
  @products = Product.all
  if params[:search]
    @products = Product.search(params[:search])
  else
    @products = Product.all
  end
  erb :'results'
  end
  </code></pre>
  
  <p>Model</p>
  
  <pre><code>class Product &lt; ActiveRecord::Base
  def self.search(search)
  where("name like ?", "%#{search}%")
  end
  </code></pre>
  
  <p>Results.erb View</p>
  
  <pre><code>&lt;% if @products.present? %&gt;
  &lt;table&gt;
  &lt;td&gt;Product Name&lt;/td&gt;&lt;td&gt;Company&lt;/td&gt;
  &lt;% @products.each do |product| %&gt;
  &lt;tr&gt;&lt;td&gt;&lt;a href="/products/&lt;%= product.id %&gt;"&gt;&lt;%=h product.name %&gt;&lt;/a&gt;   &lt;/td&gt;
  &lt;td&gt;&lt;%=h product.company.name %&gt;&lt;/td&gt;
  &lt;% end %&gt;
  &lt;% else %&gt;
  &lt;p&gt;There are no Products containing the term(s) &lt;%= params[:search] %&gt;.&lt;/p&gt;
  &lt;% end %&gt;
  &lt;/table&gt;
  </code></pre>