ruby on rails - How to retrieve selective objects from a database ? Objetcs rendered redundantly -


i'm trying retrieve objects in db can't figure out how. tried scopes without success don't think right solution.

here main involved files (unnecessary lines removed) :

# app/controllers/operators_controller.rb class operatorscontroller < applicationcontroller   def index     @operators = operator.all.sort_by_newest   end 

with following scope :

# app/models/operator.rb   scope :sort_by_newest, -> { order('created_at desc') } 

then

# app/views/operators/index.html.erb <ul class="operators">   <%= render @operators %> </ul> 

which calling following partial :

# app/views/operators/_operator.html.erb <% @operators.where(local:true).find_each |operator| %>   <li><%= link_to operator.name, operator %></li> <% end %> 

operators has local value (boolean, false default), there 3 elements local = true (then 36 local = false).

2.2.0 :003 > operator.all.count    (0.2ms)  select count(*) "operators"  => 39 2.2.0 :004 > operator.where(local: true).count    (0.4ms)  select count(*) "operators" "operators"."local" = 't'  => 3 2.2.0 :005 > operator.where(local: false).count    (0.2ms)  select count(*) "operators" "operators"."local" = 'f'  => 36 

the problem is: renders me 3 local=true elements... 39 times !

the 3 single objects need orange. rendered 39 times.

the 3 single objects need orange. rendered 39 times.

how make work?

edit :

i'd have many renders in many pages (one "local:true" elements, "global:true" elements, etc.) guess cannot modify directly operators:index method ?

you doing duplicated work. try searching operators in controller action specific query:

def index   @operators = operator.where(local: true).sort_by_newest end 

then print operator attributes, without iterator inside partial:

<li><%= link_to operator.name, operator %></li> 

Comments