Second week on RoR (with no programming background). And I have a bit of an issue, I’m doing a Metacritic type of a website. And there are going to be ratings everywhere. I decided on 0 to 33 = red 34 to 66 = orange 67 to 100 = green which looks like that
index (controller:show)
<td><% if show.reviews.count == 0 %>0
<% elsif show.reviews.average("rating").between?(33, 66) %>
<table class="orange">
<tr>
<td><b><%= number_with_precision(show.reviews.average("rating"), :precision => 0) %></b></td>
</tr>
</table>
<% elsif show.reviews.average("rating").between?(66, 100) %>
<table class="green">
<tr>
<td><%= number_with_precision(show.reviews.average("rating"), :precision => 0) %></td>
</tr>
</table>
<% elsif show.reviews.average("rating").between?(00, 33) %>
<table class="red">
<tr>
<td><%= number_with_precision(show.reviews.average("rating"), :precision => 0) %></td>
</tr>
</table>
<% end %>
</td>
My issue is that I’m gonna need to repeat that code, a lot, see (I’m only getting started:
show (controller show)
<p>
Note: <% if @ratings == 0 %>0
<% elsif @ratings.between?(33, 66) %>
<table class="orange">
<tr>
<td><b><%= number_with_precision(@ratings, :precision => 0) %></b></td>
</tr>
</table>
<% elsif @ratings.between?(66, 100) %>
<table class="green">
<tr>
<td><%= number_with_precision(@ratings, :precision => 0) %></td>
</tr>
</table>
<% elsif @ratings.between?(00, 33) %>
<table class="red">
<tr>
<td><%= number_with_precision(@ratings, :precision => 0) %></td>
</tr>
</table>
<% end %>
</p>
Somebody told me this should be a model but I don’t really know how to write it. Any help ?
First of all you should add an instance method to your
Showmodel that retrieves and caches the average rating for a show. This prevents querying the database multiple times for the same data:The code that returns the appropriate css class for a
Showcan go into a helper (e.g. theShowHelper):With this, your views become much cleaner:
And:
You could even move the generation of the entire table into a model. (Although you shouldn’t be using a table here, but that’s a different matter.)
With this you view becomes:
What Andre suggests is possible too, but it may be a bit difficult to comprehend for a beginner like yourself. This is simpler.