Simon M.
Simon M.

Reputation: 2482

Query in view - Rails

I decided to add some stats of my app in my footer so I did what I thought that was the easier, make queries in my view.

VIEW

<div>    
<h4>Quelques chiffres clés.</h4>
      Nombre total des idées: <%= Idee.all.count %> 
      <br/>Nombre total des idées publiées:<%= Idee.where(statut_id: 1).count %> 
      <br/>Nombre total des idées en cours de traitement:<%= Idee.where(statut_id: 3).count %>
      <br/>Nombre total des idées mises en place:<%= Idee.where(statut_id: 2).count %>
    </div>

But after all I don't think it's the best way to do this, so there is a better way to do this ? In my model ? controller ?

Upvotes: 0

Views: 69

Answers (2)

Rajdeep Singh
Rajdeep Singh

Reputation: 17834

Footer is available for each and every view, so it would be better to add the code in application controller, its not recommended to add queries in the view, so in your application controller

before_filter :idee_counter

def idee_counter
  idee = Idee.select(:id, :statut_id)
  @total_count = idee.size
  @total_stat_1 = idee.where(statut_id: 1).size
  @total_stat_3 = idee.where(statut_id: 3).size
  @total_stat_2 = idee.where(statut_id: 2).size  
end

Then in view

<div>    
  <h4>Quelques chiffres clés.</h4>
  Nombre total des idées: <%= @total_count %> 
  <br/>Nombre total des idées publiées:<%= @total_stat_1 %> 
  <br/>Nombre total des idées en cours de traitement:<%= @total_stat_3 %>
  <br/>Nombre total des idées mises en place:<%= @total_stat_2 %>
</div>

Hope this helps!

Upvotes: 1

joseramonc
joseramonc

Reputation: 1931

In your controller:

@idees = Idee.all

In your view:

<div>    
  <h4>Quelques chiffres clés.</h4>
  Nombre total des idées: <%= @idees.count %> 
  <br/>Nombre total des idées publiées:<%= @idees.where(statut_id: 1).count %> 
  <br/>Nombre total des idées en cours de traitement:<%= @idees.where(statut_id: 3).count %>
  <br/>Nombre total des idées mises en place:<%= @idees.where(statut_id: 2).count %>
</div>

Upvotes: 0

Related Questions