Note that there are some explanatory texts on larger screens.

plurals
  1. POTrying not to repeat myself with Rails data manipulation
    primarykey
    data
    text
    <p>I'm fairly new to rails, an an intermediate programmer in general, but I'll try to be as clear as I can.</p> <p>I have a database table for Products, which owns a field called category. Category has two possible values, call them Category1 and Category 2. The goal is to retrieve all the Products and display them in HTML organized by Category. I can make this work, but I know there has to be a better way.</p> <p>My method now is to get my Products like so:</p> <pre><code>@category1_products = Product.all(conditions: { category: "Category1" }) @category2_products = Product.all(conditions: { category: "Category2" }) </code></pre> <p>and then output the data something like this:</p> <pre><code>&lt;table&gt; &lt;tr&gt; &lt;td&gt;Category1 Name&lt;/td&gt; &lt;% @category1_products.each do |product| %&gt; &lt;td&gt;&lt;%= product.name %&gt;&lt;/td&gt; &lt;td&gt;&lt;%= product.description %&gt;&lt;/td&gt; &lt;td&gt;&lt;%= product.price %&gt;&lt;/td&gt; &lt;% end %&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Category2 Name&lt;/td&gt; &lt;% @category2_products.each do |product| %&gt; &lt;td&gt;&lt;%= product.name %&gt;&lt;/td&gt; &lt;td&gt;&lt;%= product.description %&gt;&lt;/td&gt; &lt;td&gt;&lt;%= product.price %&gt;&lt;/td&gt; &lt;% end %&gt; &lt;/tr&gt; &lt;/table&gt; </code></pre> <p>I would like to accomplish this using a single instance: get all Products at once, group them by Category, and then output them by looping through one Category at a time (including the Category Names). This seems like a pretty elementary concept to me, but I'm having trouble getting my head around it.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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