25

I think what I'm trying to do is pretty simple, and I'm really not sure why this isn't working. I'm using Rails 3.

Essentially, I'm just trying to select the distinct values from a column in an existing model, and print them out all. For the most part, this works but the .each loop in my view also ends up printing the entire array at the end of the loop. (

I a model called Attractions, and each attraction has a Category (right now the Category is hardcoded in the DB for simplicity).

This is the Attraction Model and a class method "all_categories" defined...

class Attraction < ActiveRecord::Base

  def self.all_categories
    Attraction.select("DISTINCT category")
  end

end

This is the Attraction Controller

class AttractionsController < ApplicationController
  def index
    @categories = Attraction.all_categories
    @attractions = Attraction.find(:all)
  end

  def show
    @attraction = Attraction.find(params[:id])
  end
end

This is the code in my view that is causing trouble - no rocket science, just a simple iterator, ...

  <%= @categories.each do |c| %>
    <%= c.category %><br/>
  <% end %>

Pretty simple, right? This is all running fine, BUT this is what I see when that code segment is run:

Architecture
Art
Fashion
Music
[#<Attraction category: "Architecture">, #<Attraction category: "Art">, #<Attraction category: "Fashion">, #<Attraction category: "Music">]

Why is the array at the end printed? All I want is a list of the categories:

Architecture
Art
Fashion
Music

Obviously, I'm new to Ruby/Rails, and I've tried to search all over for a solution to this. Is there something obvious that I'm missing?

Appreciate any help.

tarunsachdeva
  • 453
  • 1
  • 4
  • 13

2 Answers2

75
# Change this line with an =:
<%= @categories.each do |c| %>
# ...to this:
<%  @categories.each do |c| %>

You only want the side effects on the block of the #each method, you don't want interpolation of the returned value.

DigitalRoss
  • 143,651
  • 25
  • 248
  • 329
  • 5
    Had this same issue and gave up in the end and googled my issue hoping a stackoverflow thread would come up. This solved my issue. In my case I'm using HAML so changing "=" to "-" solved my issue. Thanks – LondonGuy Jan 31 '13 at 22:23
1

It's because it's what happen when you do

def self.all_categories
  Attraction.select("DISTINCT category")
end

It's create an Attraction Object with attribute define by your field. You can do

def self.all_categories
  Attraction.select("DISTINCT category").map(&:category)
end
Andrew Grimm
  • 78,473
  • 57
  • 200
  • 338
shingara
  • 46,608
  • 11
  • 99
  • 105
  • This works too, although I do have to implement the solution suggested by DigitalRoss in conjunction to avoid the array printing at the end. Thanks! – tarunsachdeva Oct 31 '10 at 22:20