In the tasks_controller, I defined:
def index
@tasks = Task.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: @tasks }
end
end
I have three parameters in my table: name, task, done.
now, I want to produce:
<table>
<tr>
<th>Name</th>
<th>num of tasks</th>
<th>num tasks left</th>
</tr>
<% @tasks.group_by(&:name).each do |name, tasks| %>
<tr>
<td><%= name %></td>
<td><%= tasks.size %></td>
<td> here I want to produce the number of tasks left </td>
</tr>
<% end %>
</table>
how can I get the number of tasks left? I think it should be something like:
<% @tasks.group_by(&:name).each do |name, tasks| %>
<tr>
<td><%= name %></td>
<td><%= tasks.size %></td>
<% @tasks.group_by(name, :done => "yes").each do |name, tasks| %>
<td><%= tasks.size %></td>
<% end %>
</tr>
<% end %>
You had a good idea 😉
tasks.select{ |task| task.done != 'yes' }: This will select the tasks where done is not yes, put it in an array and calculate its size (number of tasks not done yet).I strongly recommend you to set your @tasks variable like following (takes much less performances: the DB does the work for you!)
It has the same output as
@tasks.group_by(...)but is much better in execution time.