Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You should post the controller method also, to better understand the model.</p> <p>Anyway, assuming that the model Something has a string "category" column, you should not hardcode the values for the select, unless these values are fixed, in which case you might consider not using a string column.</p> <p>Here's a fast-typed example:</p> <pre><code># something_controller.rb def index @categories = Something.find_by_sql("SELECT category FROM somethings GROUP BY category").map &amp;:category @somethings = params[:category].blank? ? Something.all : Something.find_all_by_category(params[:category]) end </code></pre> <p>this is the view:</p> <pre><code>&lt;% form_tag(:action =&gt; :index) do %&gt; &lt;%= select_tag "category", options_for_select(@categories) %&gt; &lt;%= submit_tag "Filter" %&gt; &lt;% end %&gt; &lt;table&gt; &lt;tr&gt; &lt;th&gt;foo&lt;/th&gt; ... &lt;/tr&gt; &lt;% somethings.each do |something| %&gt; &lt;tr&gt; &lt;td&gt;&lt;%= something.foo %&gt;&lt;/td&gt; ... &lt;/tr&gt; &lt;% end %&gt; &lt;/table&gt; </code></pre> <p><strong>Update:</strong></p> <p>While the above code works, it was really too fastcoded, and suggests bad practise.</p> <p>Here's a better way:</p> <pre><code># app/models/Something.rb def self.all_categories find_by_sql("SELECT category FROM somethings GROUP BY category").map(&amp;:category).select {|x| x} end def self.select(category) if category find_all_by_category(category) else find :all end end #app/controllers/something_controller.rb def index @categories = Something.all_categories @somethings = Something.select(params[:category]) end </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload