سؤال

I have a loop in my view:

<% @deals.each do |d| %>


<% end %>

Deal and ListItem share the :code attribute.

If I wanted to count all the list_items that shared :code with a certain deal, how can I do this in the controller while iterating through the loop?

I understand it's bad form to access Models in the view correct? So that would rule out doing something like this in the loop right?:

<%= "#{ListItem.where(:code => d.code).count}" %>

Can I use a variable or some custom method to achieve this? Please let me know if I can clarify. Thank you!

هل كانت مفيدة؟

المحلول

You want to do all the calculation on the server in your controller action before rendering the view.

So in addition to gathering the @deals, you will also set an instance variable for the count.

def index
  @deals = Deals.all # or whatever your finder is

  @common_listitem_count = ListItem.where(code: @deals.pluck(:code)).count
end

Then just call the count instance variable in the view:

<%= @common_listitem_count %>
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top