0

This is a simple question but I can't figure out as I am new to rails.

My controller has a @neighborhoods variable which contains neighborhood records for each Business in the @businesses variable (each business has_one neighborhood)

In my view, I want to print out:

  1. Each unique neighborhood name
  2. How many of each unique neighborhood name (can be multiple since it is taken from the @businesses variable)

Currently I have:

<% @neighborhoods.uniq{|x| x.name}.each do |neighborhood| %>
   <p><%= neighborhood.name %></p>
   <%= @neighborhoods.where{name = neighborhood}.count %>
<% end %>

I know the above code is wrong, but it illustrates what I am trying to do. How can I achieve this?

3
  • Try validating from your model. validates :neighborhood, :uniqueness => {:scope => :name} Commented Jun 2, 2013 at 2:30
  • I Suppose it is @neighborhoods.where{name = neighborhood}.count Commented Jun 2, 2013 at 3:12
  • That’s a lot of logic for a view, try moving it to a model or service object. Commented Jun 2, 2013 at 4:05

1 Answer 1

3
<% @neighborhoods.group_by(&:name).each do |name, neighbourhoods| %>
  <p><%= name %></p>
  <%= neighbourhoods.count %>
<% end %>
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, but I got this error: both block arg and actual block given

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.